fix(receiving): 修复获取收货单时重复定义属性的问题
This commit is contained in:
commit
9b2cc5fc73
44
.github/agents/发布.agent.md
vendored
44
.github/agents/发布.agent.md
vendored
@ -33,10 +33,12 @@ model: GPT-5 mini (copilot)
|
||||
4. **AI 严禁展示或复述** 其中的 `host`、`username`、`privateKeyPath` 等敏感信息
|
||||
5. 发布完成后,必须通过可验证命令确认结果,再报告结论
|
||||
6. 若用户只要求协助,不主动改写本地 SSH 配置或远端敏感文件
|
||||
7. **发布前必须检查迁移状态**:若有 pending 迁移,必须先完成迁移再发布代码
|
||||
8. **迁移回退需用户明确确认**:执行 `db:migrate:undo` 前必须告知数据丢失风险并获得用户确认,不得主动触发
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
### 发布前
|
||||
### 第一步:发布前检查
|
||||
|
||||
```powershell
|
||||
npm run setup:hooks
|
||||
@ -44,26 +46,60 @@ npm run deploy:precheck
|
||||
npm run deploy:verify
|
||||
```
|
||||
|
||||
### 正式发布
|
||||
### 第二步:检查数据库迁移状态
|
||||
|
||||
```powershell
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
- 若有 `down`(pending)条目:记录迁移文件名,继续执行第三步
|
||||
- 若全部 `up`:跳过第三步,直接执行第四步
|
||||
|
||||
### 第三步:执行数据库迁移(有 pending 时)
|
||||
|
||||
```powershell
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
**执行前必须**:
|
||||
- 确认生产库已有完整备份(快照或 mysqldump)
|
||||
- 记录本次执行的迁移文件名(用于回退参考)
|
||||
- 迁移成功后再执行代码发布
|
||||
|
||||
### 第四步:发布代码
|
||||
|
||||
```powershell
|
||||
npm run deploy:prod
|
||||
```
|
||||
|
||||
### 发布后验证
|
||||
### 第五步:发布后验证
|
||||
|
||||
```powershell
|
||||
npm run deploy:version
|
||||
npm run deploy:verify
|
||||
```
|
||||
|
||||
### 回退
|
||||
### 回退流程
|
||||
|
||||
**代码回退**(不影响数据库):
|
||||
|
||||
```powershell
|
||||
npm run rollback:prod
|
||||
npm run rollback:prod -- --backup=backup-20260324123045.tar.gz
|
||||
```
|
||||
|
||||
**数据库迁移回退**(高风险,需用户明确确认):
|
||||
|
||||
```powershell
|
||||
# 回退最近一次迁移
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo --migrations-path database/migrations --env production
|
||||
|
||||
# 回退到指定迁移
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo:all --to 20260504000000-baseline.js --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
> ⚠️ **迁移回退警告**:`db:migrate:undo` 可能造成数据丢失(如 DROP COLUMN)。代码回退后如无数据异常,**不建议执行迁移回退**。只有在用户明确确认并了解风险后才可执行。
|
||||
|
||||
## 固定命令入口
|
||||
|
||||
```powershell
|
||||
|
||||
62
.github/agents/数据库.agent.md
vendored
62
.github/agents/数据库.agent.md
vendored
@ -30,17 +30,19 @@ model : GPT-5 mini (copilot)
|
||||
1. **所有数据库查询优先使用** `script/db-query.ps1`
|
||||
2. **对非测试仓库数据默认只允许只读查询**:`SELECT` / `SHOW` / `DESC` / `EXPLAIN`
|
||||
3. **禁止对非测试仓库执行** `UPDATE` / `DELETE` / `INSERT` **等写操作**
|
||||
4. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作**
|
||||
5. 如用户已明确说明是测试仓且允许写操作:
|
||||
4. **禁止直接执行任何 DDL 语句**:`ALTER TABLE` / `CREATE TABLE` / `DROP TABLE` / `ADD COLUMN` / `DROP COLUMN` / `ADD INDEX` / `DROP INDEX` 等均不得直接在数据库执行,无论是测试仓还是生产仓
|
||||
5. **所有 schema 变更必须通过迁移文件完成**:在 `database/migrations/` 下新建迁移文件,文件名格式为 `YYYYMMDDHHmmss-描述.js`,通过 `npx sequelize-cli db:migrate` 执行
|
||||
6. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作**
|
||||
7. 如用户已明确说明是测试仓且允许写操作:
|
||||
- 必须先生成影响范围确认 SQL(`COUNT(*) + 同 WHERE 条件`)
|
||||
- 明确告知风险
|
||||
- 获得用户确认后再执行
|
||||
6. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认
|
||||
7. 做接口排障时,优先链路:
|
||||
8. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认
|
||||
9. 做接口排障时,优先链路:
|
||||
- 先定位 `app/model` / `service` / `controller`
|
||||
- 再给 SQL
|
||||
- 最后执行验证并输出根因
|
||||
8. 输出要求:
|
||||
10. 输出要求:
|
||||
- 所有回复必须以 `[DB]` 开头
|
||||
- 优先给结论、关键字段和下一步建议
|
||||
|
||||
@ -91,6 +93,56 @@ powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Q
|
||||
- 报错连接失败(超时/拒绝访问)
|
||||
- 检查数据库 IP、端口、用户名密码、网络白名单
|
||||
|
||||
## Schema 变更规范(迁移文件强制要求)
|
||||
|
||||
**所有对数据库结构的变更(包括开发和生产)必须通过 Sequelize 迁移文件完成,禁止直接执行 DDL。**
|
||||
|
||||
### 迁移文件规范
|
||||
|
||||
- 位置:`database/migrations/YYYYMMDDHHmmss-描述.js`
|
||||
- 命名:时间戳 + 短横线 + 英文描述,例如 `20260504120000-add-remark-to-wms-order.js`
|
||||
- 结构:必须同时实现 `up`(变更)和 `down`(回滚)
|
||||
|
||||
### 迁移文件模板
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
// 在此写变更 SQL,例如:
|
||||
await queryInterface.addColumn('wms_order', 'remark', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '备注',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
// 在此写回滚 SQL,例如:
|
||||
await queryInterface.removeColumn('wms_order', 'remark');
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 执行命令
|
||||
|
||||
```powershell
|
||||
# 本地执行
|
||||
npx sequelize-cli db:migrate --migrations-path database/migrations
|
||||
|
||||
# 生产执行
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production
|
||||
|
||||
# 查看状态
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
### 同步 Model 文件
|
||||
|
||||
执行迁移后,必须同步更新对应的 `app/model/*.js` 文件,保持 Model 定义与数据库结构一致。
|
||||
|
||||
## 结论
|
||||
|
||||
数据库相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“数据库相关必须使用 `wms-db-agent`”这一条约束。
|
||||
|
||||
4
.github/agents/文档.agent.md
vendored
4
.github/agents/文档.agent.md
vendored
@ -11,7 +11,7 @@ model: GPT-5 mini (copilot)
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 主要文档目录:`methods/`、`docs/`
|
||||
- 主要文档目录:`methods/`
|
||||
- 常用文档文件:`AI_TOOLBOX.md`、`AI_METHOD_ROUTING.md`、`README.md`
|
||||
|
||||
## 何时必须使用本 Agent
|
||||
@ -37,7 +37,7 @@ model: GPT-5 mini (copilot)
|
||||
- 错误码变化
|
||||
- 公共请求头变化
|
||||
- 鉴权方式变化
|
||||
- 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/<docName>.json` 数组**
|
||||
- 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json`,**还必须追加一条变更记录到对应的 `methods/changes/<docName>.json` 数组**
|
||||
- 明确禁止直接手动编辑或提交 `methods/*.json` 与 `methods/changes/*.json` 文件。
|
||||
- 任何 PR 中直接修改这类文件的变更将被视为违规并可能被退回。所有对 methods JSON 的写入必须通过脚本完成,命令为 `npm run doc:api:update -- --spec=<path>`(不可绕过)。
|
||||
- 正式写入前**必须**先执行 `npm run doc:api:update -- --spec=<path> --dry-run` 进行验证;dry-run 不做写入,仅输出差异和校验结果。
|
||||
|
||||
2755
SequelizeMeta.sql
Normal file
2755
SequelizeMeta.sql
Normal file
File diff suppressed because it is too large
Load Diff
@ -9,29 +9,7 @@ class HomeController extends Controller {
|
||||
await this.ctx.service.systems.print.index.test();
|
||||
this.ctx.body = 'ok';
|
||||
}
|
||||
/**
|
||||
* Polo API 测试入口,直接透传 PoloApiService.test() 的真实返回结果。
|
||||
*
|
||||
* @return {Promise<void>} 无返回值,响应结果直接写入 ctx.body。
|
||||
*/
|
||||
async testPoloApi() {
|
||||
const {
|
||||
ctx,
|
||||
} = this;
|
||||
// 获取get参数
|
||||
const platid = ctx.params.platid;
|
||||
const result = await ctx.service.systems.poloApi.test(platid);
|
||||
ctx.body = JSON.parse(result);
|
||||
}
|
||||
async PoloApiGetWayBillCondition() {
|
||||
const {
|
||||
ctx,
|
||||
} = this;
|
||||
// 获取get参数
|
||||
const platid = ctx.params.platid;
|
||||
const result = await ctx.service.systems.poloApi.GetWayBillCondition(platid);
|
||||
ctx.body = JSON.parse(result);
|
||||
}
|
||||
|
||||
async index() {
|
||||
const {
|
||||
ctx,
|
||||
@ -394,42 +372,6 @@ class HomeController extends Controller {
|
||||
});
|
||||
}
|
||||
|
||||
async saveLog(logData, startTime) {
|
||||
const {
|
||||
ctx,
|
||||
} = this;
|
||||
|
||||
try {
|
||||
// 限制日志内容长度
|
||||
if (logData.body && logData.body.length > 65535) {
|
||||
logData.body = logData.body.substring(0, 65535);
|
||||
}
|
||||
|
||||
if (logData.result && logData.result.length > 65535) {
|
||||
logData.result = logData.result.substring(0, 65535);
|
||||
}
|
||||
|
||||
logData.use_time = Date.now() - startTime;
|
||||
|
||||
// 使用 egg-mysql 保存日志到数据库
|
||||
const result = await ctx.app.mysql.get('wms').insert('wms_api_log', {
|
||||
method: logData.method || '',
|
||||
v: logData.v || '',
|
||||
url: logData.url || '',
|
||||
created_at: ctx.app.mysql.get('wms').literals.now,
|
||||
body: logData.body || '',
|
||||
result: logData.result || '',
|
||||
use_time: logData.use_time || 0,
|
||||
});
|
||||
|
||||
return result;
|
||||
|
||||
} catch (error) {
|
||||
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
|
||||
// 可以选择记录到文件日志作为备用
|
||||
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
|
||||
}
|
||||
}
|
||||
async pda() {
|
||||
const {
|
||||
ctx,
|
||||
|
||||
68
app/controller/im.js
Normal file
68
app/controller/im.js
Normal file
@ -0,0 +1,68 @@
|
||||
const { Controller } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// 统一的返回格式
|
||||
const result = {
|
||||
code: 0,
|
||||
message: '接口错误',
|
||||
data: null,
|
||||
};
|
||||
|
||||
module.exports = class ImController extends Controller {
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
|
||||
// GET请求参数sign
|
||||
const queryData = ctx.query;
|
||||
const receivedSign = queryData.sign;
|
||||
|
||||
// 解析POST请求的body数据
|
||||
const requestData = ctx.request.body;
|
||||
const im_secret = this.config.im.secret;
|
||||
|
||||
// 验证签名:将请求体的base64字符串与预设的密钥进行拼接后进行sha256哈希
|
||||
if (!receivedSign) {
|
||||
ctx.body = { ...result, message: 'Missing signature parameter' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 将请求体转换为base64字符串
|
||||
let bodyBase64;
|
||||
try {
|
||||
bodyBase64 = Buffer.from(JSON.stringify(requestData)).toString('base64');
|
||||
} catch (err) {
|
||||
ctx.body = { ...result, message: 'Invalid request body' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 计算期望的签名
|
||||
const expectedSign = crypto
|
||||
.createHash('sha256')
|
||||
.update(bodyBase64 + im_secret)
|
||||
.digest('hex');
|
||||
|
||||
// 比对签名(使用时间恒定的比较方法防止时序攻击)
|
||||
if (!crypto.timingSafeEqual(Buffer.from(receivedSign), Buffer.from(expectedSign))) {
|
||||
ctx.body = { ...result, message: 'Invalid signature' };
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Received IM query data:', queryData);
|
||||
console.log('Received IM request data:', requestData);
|
||||
|
||||
const { method, data: data_data } = requestData || {};
|
||||
|
||||
// 通配method调用service层im的不同方法
|
||||
if (method && this.service.im[method]) {
|
||||
try {
|
||||
const { code, message, data } = await this.service.im[method](data_data);
|
||||
ctx.body = { code, message, data };
|
||||
} catch (error) {
|
||||
ctx.logger.error('IM service error:', error);
|
||||
ctx.body = { ...result, message: 'Service execution failed' };
|
||||
}
|
||||
} else {
|
||||
ctx.body = { ...result, message: 'Invalid method' };
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -58,6 +58,14 @@ module.exports = {
|
||||
ORDER_PACKED: '订单打包',
|
||||
ORDER_SHIPPED: '订单发货',
|
||||
ORDER_COMPLETE: '订单完成',
|
||||
ORDER_WAVE_ASSIGN: '分配波次',
|
||||
ORDER_WAVE_CANCEL: '取消波次',
|
||||
ORDER_STORAGE_ALLOCATE_SUCCESS: '分配储位成功',
|
||||
ORDER_STORAGE_ALLOCATE_FAILED: '分配储位失败',
|
||||
ORDER_STORAGE_UNALLOCATE_SUCCESS: '取消分配储位成功',
|
||||
ORDER_STORAGE_UNALLOCATE_FAILED: '取消分配储位失败',
|
||||
ORDER_EXPRESS_ALLOCATE_SUBMITTED: '分配快递任务已提交',
|
||||
ORDER_EXPRESS_ALLOCATE_FAILED: '分配快递失败',
|
||||
|
||||
// 库存管理
|
||||
STOCK_IN: '商品入库',
|
||||
@ -119,6 +127,9 @@ module.exports = {
|
||||
RECEIVING_DELETE_DETAIL: '删除收货明细',
|
||||
RECEIVING_BIND_PRODUCT: '绑定商品',
|
||||
RECEIVING_UPDATE_DETAIL: '修改收货明细',
|
||||
RECEIVING_UPDATE: '修改收货单',
|
||||
RECEIVING_REVIEW: '审核收货单',
|
||||
RECEIVING_REJECT: '驳回收货单',
|
||||
|
||||
// 货主管理
|
||||
STORE_CREATE: '创建货主',
|
||||
@ -152,6 +163,9 @@ module.exports = {
|
||||
SUCCESS: '成功',
|
||||
FAILED: '失败',
|
||||
PROCESSING: '处理中',
|
||||
SUBMITTED: '已提交',
|
||||
RUNNING: '进行中',
|
||||
NOT_FOUND: '未找到',
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@ -214,6 +214,41 @@ function parseRedisCacheValue(cacheValue) {
|
||||
|
||||
return JSON.parse(cacheValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用超时保护执行 Redis 命令,避免 Redis 卡顿拖慢接口响应。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @param {Promise<*>} commandPromise Redis 命令 Promise。
|
||||
* @param {string} commandName Redis 命令名。
|
||||
* @return {Promise<*>} Redis 命令执行结果。
|
||||
*/
|
||||
async function withRedisCommandTimeout(app, commandPromise, commandName) {
|
||||
const timeoutConfig = Number(app && app.config ? app.config.cacheRedisCommandTimeoutMs : 0);
|
||||
const timeoutMs = Number.isFinite(timeoutConfig) && timeoutConfig > 0 ? timeoutConfig : 800;
|
||||
|
||||
let timeoutId = null;
|
||||
|
||||
const timeoutPromise = new Promise((resolve, reject) => {
|
||||
timeoutId = setTimeout(() => {
|
||||
const timeoutError = new Error(`Redis 命令执行超时: ${commandName}, timeout=${timeoutMs}ms`);
|
||||
timeoutError.code = 'CACHE_REDIS_TIMEOUT';
|
||||
reject(timeoutError);
|
||||
}, timeoutMs);
|
||||
|
||||
if (timeoutId && typeof timeoutId.unref === 'function') {
|
||||
timeoutId.unref();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
return await Promise.race([ commandPromise, timeoutPromise ]);
|
||||
} finally {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports = {
|
||||
get businessDict() {
|
||||
return businessDict;
|
||||
@ -284,7 +319,7 @@ module.exports = {
|
||||
if (ttl <= 0) {
|
||||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||||
try {
|
||||
await cacheRedis.del(cacheKey);
|
||||
await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del');
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(this);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
@ -299,7 +334,7 @@ module.exports = {
|
||||
|
||||
if (cacheRedis && typeof cacheRedis.setex === 'function') {
|
||||
try {
|
||||
await cacheRedis.setex(cacheKey, ttl, JSON.stringify(data));
|
||||
await withRedisCommandTimeout(this, cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)), 'setex');
|
||||
|
||||
setLocalCacheValue(this, cacheKey, data, ttl);
|
||||
|
||||
@ -331,7 +366,7 @@ module.exports = {
|
||||
|
||||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||||
try {
|
||||
await cacheRedis.del(cacheKey);
|
||||
await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del');
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(this);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
@ -355,7 +390,7 @@ module.exports = {
|
||||
|
||||
if (cacheRedis && typeof cacheRedis.get === 'function') {
|
||||
try {
|
||||
const data = await cacheRedis.get(cacheKey);
|
||||
const data = await withRedisCommandTimeout(this, cacheRedis.get(cacheKey), 'get');
|
||||
if (data === undefined || data === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -2,9 +2,6 @@
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const POLYAPI_CONFIG_CACHE_KEY = 'polo_api_client:polyapi:config';
|
||||
const POLYAPI_CONFIG_CACHE_TTL_SECONDS = 60 * 60;
|
||||
|
||||
/**
|
||||
* PolyAPI 底层 HTTP 客户端。
|
||||
* 封装签名、表单编码、请求发送等通用逻辑,与业务无关。
|
||||
@ -15,124 +12,9 @@ class PoloApiClient {
|
||||
*/
|
||||
constructor(ctx) {
|
||||
this.ctx = ctx;
|
||||
this._config = null;
|
||||
this._configPromise = null;
|
||||
this.contenttype = 'json';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按需加载并缓存 PolyAPI 配置。
|
||||
*
|
||||
* 优先读取应用级缓存;缓存未命中或读取失败时,再回源数据库。
|
||||
* 数据库查到配置后,会回写到应用级缓存,缓存 TTL 为 1 小时。
|
||||
*
|
||||
* @param platid
|
||||
* @return {Promise<object|null>} PolyAPI 配置记录。
|
||||
*/
|
||||
async getConfig(platid) {
|
||||
if (this._config) {
|
||||
return this._config;
|
||||
}
|
||||
|
||||
if (!this._configPromise) {
|
||||
this._configPromise = this._loadConfig(platid).then(config => {
|
||||
this._config = config || null;
|
||||
return this._config;
|
||||
}).finally(() => {
|
||||
this._configPromise = null;
|
||||
});
|
||||
}
|
||||
|
||||
return this._configPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 PolyAPI 配置:先查缓存,未命中则查数据库。
|
||||
*
|
||||
* @param platid
|
||||
* @return {Promise<object|null>} PolyAPI 配置记录。
|
||||
*/
|
||||
async _loadConfig(platid) {
|
||||
const cachedConfig = await this._getCachedConfig(platid);
|
||||
if (cachedConfig) {
|
||||
return cachedConfig;
|
||||
}
|
||||
|
||||
const config = await this._loadConfigFromDatabase(platid);
|
||||
if (config) {
|
||||
await this._setCachedConfig(config);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从应用级缓存读取 PolyAPI 配置。
|
||||
*
|
||||
* 缓存读取失败时,返回 null 并由调用方继续回源数据库。
|
||||
*
|
||||
* @param platid
|
||||
* @return {Promise<object|null>} 缓存中的配置记录。
|
||||
*/
|
||||
async _getCachedConfig(platid) {
|
||||
if (!this.ctx.app || typeof this.ctx.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.ctx.app.getCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${platid}`);
|
||||
} catch (error) {
|
||||
if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
|
||||
this.ctx.logger.warn('[PoloApiClient._getCachedConfig] 读取缓存失败,回退数据库查询: %s', error.message);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询数据库中的 PolyAPI 配置。
|
||||
*
|
||||
* @param platid
|
||||
* @return {Promise<object|null>} 数据库中的配置记录。
|
||||
*/
|
||||
async _loadConfigFromDatabase(platid) {
|
||||
if (!this.ctx.app || !this.ctx.app.model || typeof this.ctx.app.model.query !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rows = await this.ctx.app.model.query(
|
||||
'SELECT id, interface_url, platform_code, interface_name, platid, appkey, app_secret, token, version FROM wms_express_platform WHERE platid = :platid LIMIT 1',
|
||||
{
|
||||
replacements: { platid },
|
||||
type: this.ctx.app.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
return Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 PolyAPI 配置写回应用级缓存。
|
||||
*
|
||||
* @param {object} config - PolyAPI 配置记录。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _setCachedConfig(config) {
|
||||
if (!this.ctx.app || typeof this.ctx.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const cacheValue = config && typeof config.toJSON === 'function' ? config.toJSON() : config;
|
||||
await this.ctx.app.setCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${config.platid}`, cacheValue, POLYAPI_CONFIG_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
|
||||
this.ctx.logger.warn('[PoloApiClient._setCachedConfig] 写入缓存失败,继续使用数据库结果: %s', error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起 PolyAPI 表单 POST 请求。
|
||||
*
|
||||
@ -149,9 +31,8 @@ class PoloApiClient {
|
||||
config = {},
|
||||
token,
|
||||
} = options;
|
||||
if (!config) {
|
||||
// throw new Error('未找到 polyapi 配置');
|
||||
config = await this.getConfig(633);
|
||||
if (!config || !config.interface_url) {
|
||||
throw new Error('[PoloApiClient.request] 未提供有效的 config,无法发送请求');
|
||||
}
|
||||
const configWithToken = { ...config, token: token || config.token };
|
||||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||||
@ -179,6 +60,17 @@ class PoloApiClient {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起 PolyAPI GET 请求。
|
||||
*
|
||||
* @param {object} options - 请求参数。
|
||||
* @param {string} options.method - 远端接口方法名。
|
||||
* @param {object|string} [options.bizcontent={}] - 业务参数内容。
|
||||
* @param {object} [options.config={}] - 平台配置。
|
||||
* @param {string} [options.token] - 可选 token,传入时优先覆盖配置 token。
|
||||
* @return {Promise<any>} 接口响应 data。
|
||||
*/
|
||||
async get(options = {}) {
|
||||
const {
|
||||
method,
|
||||
@ -186,9 +78,8 @@ class PoloApiClient {
|
||||
config = {},
|
||||
token,
|
||||
} = options;
|
||||
if (!config) {
|
||||
// throw new Error('未找到 polyapi 配置');
|
||||
config = await this.getConfig(633);
|
||||
if (!config || !config.interface_url) {
|
||||
throw new Error('[PoloApiClient.get] 未提供有效的 config,无法发送请求');
|
||||
}
|
||||
const configWithToken = { ...config, token: token || config.token };
|
||||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||||
@ -221,10 +112,11 @@ class PoloApiClient {
|
||||
|
||||
/**
|
||||
* 组装签名所需的请求参数。
|
||||
* @param config
|
||||
* @param method
|
||||
* @param platid
|
||||
* @param bizcontent
|
||||
* @param {object} config 平台配置对象。
|
||||
* @param {string} method 接口方法名。
|
||||
* @param {number|string} platid 平台 ID。
|
||||
* @param {object|string} bizcontent 业务参数。
|
||||
* @return {object} 签名参数映射。
|
||||
*/
|
||||
_buildSignMap(config, method, platid, bizcontent) {
|
||||
const normalizedBizcontent = bizcontent && typeof bizcontent === 'object'
|
||||
@ -245,8 +137,9 @@ class PoloApiClient {
|
||||
|
||||
/**
|
||||
* 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。
|
||||
* @param signMap
|
||||
* @param secret
|
||||
* @param {object} signMap 待签名参数映射。
|
||||
* @param {string} secret 签名密钥。
|
||||
* @return {string} 签名原文字符串。
|
||||
*/
|
||||
_getSignText(signMap, secret) {
|
||||
let sb = '' + secret;
|
||||
@ -259,8 +152,9 @@ class PoloApiClient {
|
||||
|
||||
/**
|
||||
* MD5 摘要。
|
||||
* @param text
|
||||
* @param encoding
|
||||
* @param {string} text 待摘要文本。
|
||||
* @param {BufferEncoding} [encoding='utf8'] 文本编码。
|
||||
* @return {string} 十六进制 MD5 值。
|
||||
*/
|
||||
_md5(text, encoding = 'utf8') {
|
||||
return crypto.createHash('md5').update(text, encoding).digest('hex');
|
||||
@ -268,7 +162,8 @@ class PoloApiClient {
|
||||
|
||||
/**
|
||||
* 将参数编码为 application/x-www-form-urlencoded。
|
||||
* @param map
|
||||
* @param {object} map 表单参数映射。
|
||||
* @return {string} URL 编码后的查询串。
|
||||
*/
|
||||
_encodeForm(map) {
|
||||
const params = new URLSearchParams();
|
||||
@ -281,7 +176,8 @@ class PoloApiClient {
|
||||
|
||||
/**
|
||||
* 格式化日期 → yyyy-MM-dd HH:mm:ss。
|
||||
* @param date
|
||||
* @param {Date} date 日期对象。
|
||||
* @return {string} 格式化后的时间字符串。
|
||||
*/
|
||||
_formatDate(date) {
|
||||
const pad = n => (n < 10 ? '0' + n : n);
|
||||
@ -291,9 +187,10 @@ class PoloApiClient {
|
||||
|
||||
/**
|
||||
* 格式化取件日期。
|
||||
* @param year
|
||||
* @param month
|
||||
* @param day
|
||||
* @param {number} year 年。
|
||||
* @param {number} month 月。
|
||||
* @param {number} day 日。
|
||||
* @return {string} 取件日期时间字符串。
|
||||
*/
|
||||
_formatPickupDate(year, month, day) {
|
||||
const pad = n => (n < 10 ? '0' + n : n);
|
||||
|
||||
107
app/model/embargo_policy.js
Normal file
107
app/model/embargo_policy.js
Normal file
@ -0,0 +1,107 @@
|
||||
// app/model/embargo_policy.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING, ENUM, TEXT, DATEONLY, DATE, BOOLEAN, BIGINT } = app.Sequelize;
|
||||
|
||||
const EmbargoPolicy = app.model.define('wms_embargo_policies', {
|
||||
id: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: 'ID',
|
||||
},
|
||||
policy_name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '策略名称',
|
||||
},
|
||||
status: {
|
||||
type: ENUM('ACTIVE', 'INACTIVE', 'PENDING', 'EXPIRED'),
|
||||
allowNull: true,
|
||||
defaultValue: 'PENDING',
|
||||
comment: '状态',
|
||||
},
|
||||
embargo_scope: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '禁运范围(数组)',
|
||||
},
|
||||
start_date: {
|
||||
type: DATEONLY,
|
||||
allowNull: false,
|
||||
comment: '生效开始日期',
|
||||
},
|
||||
end_date: {
|
||||
type: DATEONLY,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '结束日期',
|
||||
},
|
||||
is_permanent: {
|
||||
type: BOOLEAN,
|
||||
allowNull: true,
|
||||
defaultValue: false,
|
||||
comment: '是否永久有效',
|
||||
},
|
||||
description: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '策略描述',
|
||||
},
|
||||
created_by: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '创建人',
|
||||
},
|
||||
updated_by: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '更新人',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_embargo_policies',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
comment: '禁运策略主表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_status',
|
||||
fields: [ 'status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_dates',
|
||||
fields: [ 'start_date', 'end_date' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_created_at',
|
||||
fields: [ 'created_at' ],
|
||||
},
|
||||
{
|
||||
name: 'warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return EmbargoPolicy;
|
||||
};
|
||||
@ -144,7 +144,7 @@ module.exports = app => {
|
||||
comment: '操作人ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20),
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
@ -173,8 +173,14 @@ module.exports = app => {
|
||||
comment: '快递面单打印记录表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_express_id',
|
||||
fields: [ 'express_id' ],
|
||||
unique: true,
|
||||
name: 'uk_express_print',
|
||||
fields: [ 'express_id', 'print_status' ],
|
||||
},
|
||||
{
|
||||
unique: true,
|
||||
name: 'uk_request_id',
|
||||
fields: [ 'request_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_order_id',
|
||||
@ -185,18 +191,37 @@ module.exports = app => {
|
||||
fields: [ 'express_no' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_request_id',
|
||||
unique: true,
|
||||
fields: [ 'request_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
name: 'idx_platform',
|
||||
fields: [ 'platform' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_print_status',
|
||||
fields: [ 'print_status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_create_time',
|
||||
fields: [ 'create_time' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_batch_no',
|
||||
fields: [ 'batch_no' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_template_id',
|
||||
fields: [ 'template_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_printer_config_id',
|
||||
fields: [ 'printer_config_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_print_time',
|
||||
fields: [ 'print_time' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, DATE, ENUM, JSON, TEXT } = app.Sequelize;
|
||||
const { STRING, BIGINT, DATE, ENUM, JSON, TEXT } = app.Sequelize;
|
||||
|
||||
const OperationLog = app.model.define('operation_log', {
|
||||
id: {
|
||||
@ -49,8 +49,8 @@ module.exports = app => {
|
||||
comment: '外部日志ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
before_changes: {
|
||||
|
||||
@ -216,8 +216,8 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '系统物流公司名称',
|
||||
},
|
||||
|
||||
basket_number:{
|
||||
|
||||
basket_number: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '筐号',
|
||||
@ -393,6 +393,12 @@ module.exports = app => {
|
||||
defaultValue: 0,
|
||||
comment: '波次ID,0表示未分配',
|
||||
},
|
||||
wave_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '波次号,空字符串表示未分配',
|
||||
},
|
||||
// 状态机字段
|
||||
post_status: {
|
||||
type: ENUM(...StatusEnum.POST_STATUS),
|
||||
|
||||
@ -15,6 +15,7 @@ const {
|
||||
buildTableComment,
|
||||
buildTableOptions,
|
||||
buildIndexOptions,
|
||||
buildColumnLine,
|
||||
buildColumnLines,
|
||||
buildIndexLines,
|
||||
parseManagedTableName,
|
||||
@ -109,9 +110,33 @@ module.exports = app => {
|
||||
class OrderDeliveryFactory {
|
||||
constructor() {
|
||||
this.modelCache = new Map();
|
||||
this.inflightInitCache = new Map();
|
||||
this.app = app;
|
||||
}
|
||||
|
||||
/**
|
||||
* 复用并发中的模型初始化,避免重复执行建模与结构自检。
|
||||
* @param {string} lockKey 并发锁键。
|
||||
* @param {Function} initializer 初始化函数。
|
||||
* @return {Promise<Object>} 模型实例。
|
||||
*/
|
||||
async runModelInitializer(lockKey, initializer) {
|
||||
if (this.inflightInitCache.has(lockKey)) {
|
||||
return await this.inflightInitCache.get(lockKey);
|
||||
}
|
||||
|
||||
const initPromise = (async () => {
|
||||
try {
|
||||
return await initializer();
|
||||
} finally {
|
||||
this.inflightInitCache.delete(lockKey);
|
||||
}
|
||||
})();
|
||||
|
||||
this.inflightInitCache.set(lockKey, initPromise);
|
||||
return await initPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取配送域车道常量。
|
||||
* @return {Object} 车道常量。
|
||||
@ -198,32 +223,39 @@ module.exports = app => {
|
||||
*/
|
||||
async getModelByTableName(tableName) {
|
||||
const cacheKey = `table_${tableName}`;
|
||||
const lockKey = `init_table_${tableName}`;
|
||||
|
||||
if (this.modelCache.has(cacheKey)) {
|
||||
return this.modelCache.get(cacheKey);
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = parseManagedTableName(tableName);
|
||||
if (!parsed) {
|
||||
throw new Error(`表 ${tableName} 不是订单工厂管理表`);
|
||||
return await this.runModelInitializer(lockKey, async () => {
|
||||
if (this.modelCache.has(cacheKey)) {
|
||||
return this.modelCache.get(cacheKey);
|
||||
}
|
||||
|
||||
const tableExists = await this.checkTableExists(tableName);
|
||||
if (!tableExists) {
|
||||
throw new Error(`表 ${tableName} 不存在`);
|
||||
try {
|
||||
const parsed = parseManagedTableName(tableName);
|
||||
if (!parsed) {
|
||||
throw new Error(`表 ${tableName} 不是订单工厂管理表`);
|
||||
}
|
||||
|
||||
const tableExists = await this.checkTableExists(tableName);
|
||||
if (!tableExists) {
|
||||
throw new Error(`表 ${tableName} 不存在`);
|
||||
}
|
||||
|
||||
const DynamicModel = this.buildManagedModel(parsed.warehouseId, parsed.type, tableName);
|
||||
await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId, DynamicModel);
|
||||
|
||||
this.modelCache.set(cacheKey, DynamicModel);
|
||||
return DynamicModel;
|
||||
|
||||
} catch (error) {
|
||||
this.app.logger.error(`获取模型失败 ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const DynamicModel = this.buildManagedModel(parsed.warehouseId, parsed.type, tableName);
|
||||
await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId, DynamicModel);
|
||||
|
||||
this.modelCache.set(cacheKey, DynamicModel);
|
||||
return DynamicModel;
|
||||
|
||||
} catch (error) {
|
||||
this.app.logger.error(`获取模型失败 ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -237,29 +269,39 @@ module.exports = app => {
|
||||
const modelType = this.resolveModelType(type);
|
||||
const tableName = this.generateTableName(warehouseIdStr, modelType);
|
||||
const cacheKey = `${warehouseIdStr}_${modelType}`;
|
||||
const tableCacheKey = `table_${tableName}`;
|
||||
// 与 getModelByTableName 统一使用“物理表名锁”,避免不同入口并发重复初始化同一张表
|
||||
const lockKey = `init_table_${tableName}`;
|
||||
|
||||
// 检查缓存
|
||||
if (this.modelCache.has(cacheKey)) {
|
||||
return this.modelCache.get(cacheKey);
|
||||
}
|
||||
|
||||
try {
|
||||
const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName);
|
||||
await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel);
|
||||
return await this.runModelInitializer(lockKey, async () => {
|
||||
if (this.modelCache.has(cacheKey)) {
|
||||
return this.modelCache.get(cacheKey);
|
||||
}
|
||||
|
||||
// 设置关联关系
|
||||
this.setupAssociations(DynamicModel, warehouseIdStr, modelType);
|
||||
try {
|
||||
const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName);
|
||||
await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel);
|
||||
|
||||
// 缓存模型
|
||||
this.modelCache.set(cacheKey, DynamicModel);
|
||||
this.app.logger.info(`创建动态模型成功: ${tableName}`);
|
||||
// 设置关联关系
|
||||
this.setupAssociations(DynamicModel, warehouseIdStr, modelType);
|
||||
|
||||
return DynamicModel;
|
||||
// 缓存模型(按业务键和表名键双写,避免跨入口重复初始化)
|
||||
this.modelCache.set(cacheKey, DynamicModel);
|
||||
this.modelCache.set(tableCacheKey, DynamicModel);
|
||||
this.app.logger.info(`创建动态模型成功: ${tableName}`);
|
||||
|
||||
} catch (error) {
|
||||
this.app.logger.error(`创建动态模型失败 ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
return DynamicModel;
|
||||
|
||||
} catch (error) {
|
||||
this.app.logger.error(`创建动态模型失败 ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -557,6 +599,11 @@ module.exports = app => {
|
||||
const tableColumns = await queryInterface.describeTable(tableName);
|
||||
const expectedAttributes = this.getTableAttributes(type);
|
||||
const columnNames = new Set(Object.keys(tableColumns || {}));
|
||||
const quotedTableName = quoteIdentifier(tableName);
|
||||
|
||||
// 收集需要检查的列
|
||||
const notNullColumns = [];
|
||||
const numericColumns = [];
|
||||
|
||||
for (const columnName of Object.keys(expectedAttributes)) {
|
||||
if (!columnNames.has(columnName)) {
|
||||
@ -564,45 +611,69 @@ module.exports = app => {
|
||||
}
|
||||
|
||||
const expectedAttribute = expectedAttributes[columnName];
|
||||
const quotedTableName = quoteIdentifier(tableName);
|
||||
const quotedColumnName = quoteIdentifier(columnName);
|
||||
|
||||
if (expectedAttribute.allowNull === false) {
|
||||
const [ nullRows ] = await sequelize.query(
|
||||
`SELECT 1 AS violationFound FROM ${quotedTableName} WHERE ${quotedColumnName} IS NULL LIMIT 1`
|
||||
);
|
||||
|
||||
if (Array.isArray(nullRows) && nullRows.length > 0) {
|
||||
throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL');
|
||||
}
|
||||
notNullColumns.push(columnName);
|
||||
}
|
||||
|
||||
const numericConstraint = parseNumericConstraint(expectedAttribute);
|
||||
|
||||
if (!numericConstraint) {
|
||||
continue;
|
||||
if (numericConstraint) {
|
||||
numericColumns.push({ columnName, numericConstraint });
|
||||
}
|
||||
}
|
||||
|
||||
const [ rangeRows ] = await sequelize.query(
|
||||
`SELECT 1 AS violationFound FROM ${quotedTableName}
|
||||
WHERE ${quotedColumnName} IS NOT NULL
|
||||
AND (${quotedColumnName} < :minValue OR ${quotedColumnName} > :maxValue)
|
||||
LIMIT 1`,
|
||||
{
|
||||
replacements: {
|
||||
minValue: numericConstraint.min,
|
||||
maxValue: numericConstraint.max,
|
||||
},
|
||||
// 一条 SQL 检查所有 NOT NULL 约束
|
||||
if (notNullColumns.length > 0) {
|
||||
const conditions = notNullColumns
|
||||
.map(col => `${quoteIdentifier(col)} IS NULL`)
|
||||
.join(' OR ');
|
||||
const selectCols = notNullColumns
|
||||
.map(col => `MAX(CASE WHEN ${quoteIdentifier(col)} IS NULL THEN 1 ELSE 0 END) AS ${quoteIdentifier(col)}`)
|
||||
.join(', ');
|
||||
const [ nullRows ] = await sequelize.query(
|
||||
`SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1`
|
||||
);
|
||||
|
||||
if (Array.isArray(nullRows) && nullRows.length > 0) {
|
||||
const row = nullRows[0];
|
||||
for (const columnName of notNullColumns) {
|
||||
if (row[columnName] === 1) {
|
||||
throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 一条 SQL 检查所有数值范围约束
|
||||
if (numericColumns.length > 0) {
|
||||
const selectCols = numericColumns
|
||||
.map(({ columnName, numericConstraint }) => {
|
||||
const qCol = quoteIdentifier(columnName);
|
||||
return `MAX(CASE WHEN ${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}) THEN 1 ELSE 0 END) AS ${quoteIdentifier(columnName)}`;
|
||||
})
|
||||
.join(', ');
|
||||
const conditions = numericColumns
|
||||
.map(({ columnName, numericConstraint }) => {
|
||||
const qCol = quoteIdentifier(columnName);
|
||||
return `(${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}))`;
|
||||
})
|
||||
.join(' OR ');
|
||||
const [ rangeRows ] = await sequelize.query(
|
||||
`SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1`
|
||||
);
|
||||
|
||||
if (Array.isArray(rangeRows) && rangeRows.length > 0) {
|
||||
throw buildManagedTableConstraintError(
|
||||
tableName,
|
||||
columnName,
|
||||
'NUMERIC_RANGE',
|
||||
`expected=[${numericConstraint.min}, ${numericConstraint.max}]`
|
||||
);
|
||||
const row = rangeRows[0];
|
||||
for (const { columnName, numericConstraint } of numericColumns) {
|
||||
if (row[columnName] === 1) {
|
||||
throw buildManagedTableConstraintError(
|
||||
tableName,
|
||||
columnName,
|
||||
'NUMERIC_RANGE',
|
||||
`expected=[${numericConstraint.min}, ${numericConstraint.max}]`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -628,14 +699,60 @@ module.exports = app => {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (tableExists) {
|
||||
await this.assertManagedTableDataConstraints(tableName, modelType);
|
||||
if (!tableExists) {
|
||||
await dynamicModel.sync({ force: false });
|
||||
return true;
|
||||
}
|
||||
|
||||
await dynamicModel.sync({ alter: true });
|
||||
await this.assertManagedTableDataConstraints(tableName, modelType);
|
||||
await this.alterManagedTableSchema(tableName, modelType, warehouseId, dynamicModel);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} type 模型类型。
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @param {Object} dynamicModel 已构建的动态模型(用于索引同步)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async alterManagedTableSchema(tableName, type, warehouseId, dynamicModel) {
|
||||
const queryInterface = this.app.model.getQueryInterface();
|
||||
const sequelize = this.app.model;
|
||||
const actualColumns = await queryInterface.describeTable(tableName);
|
||||
const expectedAttributes = this.getTableAttributes(type);
|
||||
const quotedTableName = quoteIdentifier(tableName);
|
||||
const actualColumnNames = new Set(Object.keys(actualColumns || {}));
|
||||
const expectedColumnNames = Object.keys(expectedAttributes);
|
||||
const clauses = [];
|
||||
|
||||
// ADD 新增列 / CHANGE 变更列
|
||||
for (const columnName of expectedColumnNames) {
|
||||
const columnDef = buildColumnLine(columnName, expectedAttributes[columnName]);
|
||||
if (!actualColumnNames.has(columnName)) {
|
||||
clauses.push(`ADD COLUMN ${columnDef}`);
|
||||
} else {
|
||||
clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`);
|
||||
}
|
||||
}
|
||||
|
||||
// DROP 多余列(现有表有但期望模型没有的列)
|
||||
const expectedColumnSet = new Set(expectedColumnNames);
|
||||
for (const columnName of actualColumnNames) {
|
||||
if (!expectedColumnSet.has(columnName)) {
|
||||
clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (clauses.length > 0) {
|
||||
await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`);
|
||||
}
|
||||
|
||||
// 索引同步仍委托 Sequelize sync({ alter: true }) 处理(仅触发索引差异)
|
||||
await dynamicModel.sync({ alter: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前库中已存在的订单工厂目标表。
|
||||
* @return {Promise<Array<string>>} 目标表名列表。
|
||||
@ -720,6 +837,7 @@ module.exports = app => {
|
||||
*/
|
||||
clearCache() {
|
||||
this.modelCache.clear();
|
||||
this.inflightInitCache.clear();
|
||||
clearShardWarehouseValidationCache(this.app);
|
||||
this.app.logger.info('模型缓存已清理');
|
||||
}
|
||||
|
||||
@ -236,10 +236,20 @@ function formatDefaultValue(defaultValue) {
|
||||
* @return {string} DDL 列片段。
|
||||
*/
|
||||
function buildColumnLine(columnName, attribute) {
|
||||
const parts = [ `\`${columnName}\``, attribute.type && typeof attribute.type.toSql === 'function'
|
||||
? attribute.type.toSql()
|
||||
: String(attribute.type || ''),
|
||||
];
|
||||
let typeSql;
|
||||
|
||||
if (attribute.type && Array.isArray(attribute.type.values)) {
|
||||
// ENUM 类型:type.toSql() 内部调 this.sequelize.escape(),sequelize 引用可能未绑定
|
||||
// 直接用安全转义构造,避免依赖 sequelize 实例
|
||||
const escaped = attribute.type.values.map(v => `'${String(v).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`).join(', ');
|
||||
typeSql = `ENUM(${escaped})`;
|
||||
} else if (attribute.type && typeof attribute.type.toSql === 'function') {
|
||||
typeSql = attribute.type.toSql();
|
||||
} else {
|
||||
typeSql = String(attribute.type || '');
|
||||
}
|
||||
|
||||
const parts = [ `\`${columnName}\``, typeSql ];
|
||||
|
||||
if (attribute.allowNull === false) {
|
||||
parts.push('NOT NULL');
|
||||
@ -515,6 +525,7 @@ module.exports = {
|
||||
buildTableComment,
|
||||
buildTableOptions,
|
||||
buildIndexOptions,
|
||||
buildColumnLine,
|
||||
buildColumnLines,
|
||||
buildIndexLines,
|
||||
parseManagedTableName,
|
||||
|
||||
167
app/model/picking_strategy.js
Normal file
167
app/model/picking_strategy.js
Normal file
@ -0,0 +1,167 @@
|
||||
// app/model/picking_strategy.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, TINYINT, BOOLEAN, JSON, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const PickingStrategy = app.model.define('wms_picking_strategy', {
|
||||
id: {
|
||||
type: INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '策略ID',
|
||||
},
|
||||
strategy_name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '策略名称',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
strategy_type: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
comment: '策略类型:1-散单 2-团购',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '状态:1-启用 0-停用',
|
||||
},
|
||||
order_min_sku: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '订单最小SKU种类数',
|
||||
},
|
||||
order_max_sku: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 999,
|
||||
comment: '订单最大SKU种类数',
|
||||
},
|
||||
order_min_qty: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '订单最小商品总数',
|
||||
},
|
||||
order_max_qty: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 999,
|
||||
comment: '订单最大商品总数',
|
||||
},
|
||||
min_same_structure: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '最小相同结构订单数',
|
||||
},
|
||||
max_same_structure: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 999,
|
||||
comment: '最大相同结构订单数',
|
||||
},
|
||||
require_same_express: {
|
||||
type: BOOLEAN,
|
||||
allowNull: true,
|
||||
defaultValue: false,
|
||||
comment: '是否要求相同快递',
|
||||
},
|
||||
allow_cross_owner: {
|
||||
type: BOOLEAN,
|
||||
allowNull: true,
|
||||
defaultValue: true,
|
||||
comment: '是否允许跨货主',
|
||||
},
|
||||
batch_mode: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
comment: '拣货模式:1-单品单件 2-先拣后分 3-边拣边分 4-边拣边分H型 5-播种墙 6-流利架',
|
||||
},
|
||||
batch_max_orders: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 20,
|
||||
comment: '批次最大订单数',
|
||||
},
|
||||
batch_max_skus: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 50,
|
||||
comment: '批次最大SKU总数',
|
||||
},
|
||||
group_batch_max_orders: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '团购批次最大订单数(相同结构)',
|
||||
},
|
||||
allowed_owners: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '允许的货主ID列表',
|
||||
},
|
||||
allowed_expresses: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '允许的快递编码列表',
|
||||
},
|
||||
allowed_provinces: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '允许的省份列表',
|
||||
},
|
||||
allowed_platforms: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '允许的平台列表',
|
||||
},
|
||||
description: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '策略描述',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '创建人姓名',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
update_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_picking_strategy',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
comment: '拣货策略配置表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_warehouse_type',
|
||||
fields: [ 'warehouse_id', 'strategy_type', 'status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_batch_mode',
|
||||
fields: [ 'batch_mode', 'strategy_type' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return PickingStrategy;
|
||||
};
|
||||
96
app/model/platform_print_config.js
Normal file
96
app/model/platform_print_config.js
Normal file
@ -0,0 +1,96 @@
|
||||
// app/model/platform_print_config.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const PlatformPrintConfig = app.model.define('wms_platform_print_config', {
|
||||
id: {
|
||||
type: BIGINT,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
platform: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
comment: '平台名称',
|
||||
},
|
||||
platform_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '平台代码',
|
||||
},
|
||||
print_port: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
comment: '打印服务端口',
|
||||
},
|
||||
print_url: {
|
||||
type: STRING(200),
|
||||
allowNull: true,
|
||||
comment: '打印服务URL',
|
||||
},
|
||||
protocol_type: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
defaultValue: 'WEBSOCKET',
|
||||
comment: '协议类型:WEBSOCKET,HTTP',
|
||||
},
|
||||
status: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
defaultValue: 'ACTIVE',
|
||||
comment: '状态:ACTIVE-启用,DISABLED-禁用',
|
||||
},
|
||||
retry_count: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 3,
|
||||
comment: '重试次数',
|
||||
},
|
||||
timeout_seconds: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 30,
|
||||
comment: '超时时间(秒)',
|
||||
},
|
||||
description: {
|
||||
type: STRING(200),
|
||||
allowNull: true,
|
||||
comment: '描述',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
update_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_platform_print_config',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
comment: '平台打印端口配置表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_platform',
|
||||
unique: true,
|
||||
fields: [ 'platform' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_platform_code',
|
||||
fields: [ 'platform_code' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return PlatformPrintConfig;
|
||||
};
|
||||
98
app/model/print_log.js
Normal file
98
app/model/print_log.js
Normal file
@ -0,0 +1,98 @@
|
||||
// app/model/print_log.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TEXT, JSON, DATE } = app.Sequelize;
|
||||
|
||||
const PrintLog = app.model.define('wms_print_log', {
|
||||
id: {
|
||||
type: BIGINT,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
print_record_id: {
|
||||
type: BIGINT,
|
||||
allowNull: false,
|
||||
comment: '打印记录ID',
|
||||
},
|
||||
log_type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
comment: '日志类型:CONNECT-连接,PRINT-打印,RETRY-重试,ERROR-错误,SUCCESS-成功',
|
||||
},
|
||||
log_level: {
|
||||
type: STRING(10),
|
||||
allowNull: true,
|
||||
defaultValue: 'INFO',
|
||||
comment: '日志级别:INFO,WARN,ERROR',
|
||||
},
|
||||
log_content: {
|
||||
type: TEXT,
|
||||
allowNull: false,
|
||||
comment: '日志内容',
|
||||
},
|
||||
request_data: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '请求数据',
|
||||
},
|
||||
response_data: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '响应数据',
|
||||
},
|
||||
websocket_status: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: 'WebSocket状态',
|
||||
},
|
||||
error_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '错误代码',
|
||||
},
|
||||
ip_address: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: 'IP地址',
|
||||
},
|
||||
user_agent: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '用户代理',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_print_log',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
comment: '打印日志表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_print_record',
|
||||
fields: [ 'print_record_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_log_type',
|
||||
fields: [ 'log_type' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_create_time',
|
||||
fields: [ 'create_time' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_error_code',
|
||||
fields: [ 'error_code' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return PrintLog;
|
||||
};
|
||||
@ -46,7 +46,7 @@ module.exports = app => {
|
||||
comment: '页面高度(mm)',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20),
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
comment: '关联仓库ID',
|
||||
},
|
||||
is_default: {
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, DATE } = app.Sequelize;
|
||||
const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const StockUnit = app.model.define('wms_stock_unit', {
|
||||
id: {
|
||||
@ -12,7 +12,7 @@ module.exports = app => {
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: INTEGER,
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '仓库ID,NULL表示系统默认',
|
||||
|
||||
@ -3,10 +3,15 @@
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE, TINYINT, JSON: JSON_TYPE } = app.Sequelize;
|
||||
const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5;
|
||||
const DEFAULT_MAX_WAVE_QUANTITY = 500;
|
||||
const DEFAULT_SUBJECT_CONFIG = Object.freeze({
|
||||
max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT,
|
||||
max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY,
|
||||
min_group_order_fetch_quantity: 13,
|
||||
default_express_code: 'STO',
|
||||
default_platform_code: 'TB',
|
||||
group_wave_prefix: 'B',
|
||||
delete_order_wave_prefix: 'A',
|
||||
});
|
||||
|
||||
const normalizeSubjectConfigText = (value, defaultValue) => {
|
||||
@ -34,6 +39,12 @@ module.exports = app => {
|
||||
throw new Error(`${fieldName} 必须是布尔值`);
|
||||
};
|
||||
|
||||
/**
|
||||
* 规范化主体配置,确保默认值与字段约束一致。
|
||||
*
|
||||
* @param {Object|string|null|undefined} rawValue 主体配置原始值。
|
||||
* @return {Object} 规范化后的主体配置对象。
|
||||
*/
|
||||
const normalizeSubjectConfig = rawValue => {
|
||||
if (rawValue === undefined || rawValue === null || rawValue === '') {
|
||||
return { ...DEFAULT_SUBJECT_CONFIG };
|
||||
@ -67,6 +78,28 @@ module.exports = app => {
|
||||
normalized.max_notice_webhook_count = limit;
|
||||
}
|
||||
|
||||
const rawMaxWaveQuantity = parsed.max_wave_quantity;
|
||||
if (rawMaxWaveQuantity === undefined || rawMaxWaveQuantity === null || rawMaxWaveQuantity === '') {
|
||||
normalized.max_wave_quantity = DEFAULT_MAX_WAVE_QUANTITY;
|
||||
} else {
|
||||
const maxWaveQuantity = Number(rawMaxWaveQuantity);
|
||||
if (!Number.isInteger(maxWaveQuantity) || maxWaveQuantity <= 0) {
|
||||
throw new Error('subject_config.max_wave_quantity 必须是大于 0 的整数');
|
||||
}
|
||||
normalized.max_wave_quantity = maxWaveQuantity;
|
||||
}
|
||||
|
||||
const rawMinGroupOrderFetchQuantity = parsed.min_group_order_fetch_quantity;
|
||||
if (rawMinGroupOrderFetchQuantity === undefined || rawMinGroupOrderFetchQuantity === null || rawMinGroupOrderFetchQuantity === '') {
|
||||
normalized.min_group_order_fetch_quantity = DEFAULT_SUBJECT_CONFIG.min_group_order_fetch_quantity;
|
||||
} else {
|
||||
const minGroupOrderFetchQuantity = Number(rawMinGroupOrderFetchQuantity);
|
||||
if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) {
|
||||
throw new Error('subject_config.min_group_order_fetch_quantity 必须是大于 0 的整数');
|
||||
}
|
||||
normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity;
|
||||
}
|
||||
|
||||
normalized.default_express_code = normalizeSubjectConfigText(
|
||||
parsed.default_express_code,
|
||||
DEFAULT_SUBJECT_CONFIG.default_express_code
|
||||
@ -76,6 +109,36 @@ module.exports = app => {
|
||||
DEFAULT_SUBJECT_CONFIG.default_platform_code
|
||||
);
|
||||
|
||||
const rawGroupWavePrefix = parsed.group_wave_prefix;
|
||||
if (rawGroupWavePrefix === undefined || rawGroupWavePrefix === null || rawGroupWavePrefix === '') {
|
||||
normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix;
|
||||
} else {
|
||||
const groupWavePrefix = String(rawGroupWavePrefix).trim();
|
||||
if (groupWavePrefix === '') {
|
||||
normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix;
|
||||
} else {
|
||||
if (groupWavePrefix.length > 5) {
|
||||
throw new Error('subject_config.group_wave_prefix 最多 5 个字符');
|
||||
}
|
||||
normalized.group_wave_prefix = groupWavePrefix;
|
||||
}
|
||||
}
|
||||
|
||||
const rawDeleteOrderWavePrefix = parsed.delete_order_wave_prefix;
|
||||
if (rawDeleteOrderWavePrefix === undefined || rawDeleteOrderWavePrefix === null || rawDeleteOrderWavePrefix === '') {
|
||||
normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix;
|
||||
} else {
|
||||
const deleteOrderWavePrefix = String(rawDeleteOrderWavePrefix).trim();
|
||||
if (deleteOrderWavePrefix === '') {
|
||||
normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix;
|
||||
} else {
|
||||
if (deleteOrderWavePrefix.length > 5) {
|
||||
throw new Error('subject_config.delete_order_wave_prefix 最多 5 个字符');
|
||||
}
|
||||
normalized.delete_order_wave_prefix = deleteOrderWavePrefix;
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) {
|
||||
normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled');
|
||||
}
|
||||
|
||||
94
app/model/system_log.js
Normal file
94
app/model/system_log.js
Normal file
@ -0,0 +1,94 @@
|
||||
// app/model/system_log.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TEXT, DATE, INTEGER } = app.Sequelize;
|
||||
|
||||
const SystemLog = app.model.define('wms_system_log', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: 'ID',
|
||||
},
|
||||
method: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '方法名',
|
||||
},
|
||||
v: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '版本',
|
||||
},
|
||||
url: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '请求URL',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '创建时间',
|
||||
},
|
||||
body: {
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
comment: '请求体',
|
||||
},
|
||||
result: {
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
comment: '响应体',
|
||||
},
|
||||
use_time: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
comment: '耗时',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '更新时间',
|
||||
},
|
||||
delete_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
headers: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '请求头',
|
||||
},
|
||||
auth: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '认证信息',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '门店ID',
|
||||
},
|
||||
device: {
|
||||
type: STRING(10),
|
||||
allowNull: true,
|
||||
comment: '设备',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_system_log',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
comment: '系统日志表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'store_id',
|
||||
fields: [ 'store_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return SystemLog;
|
||||
};
|
||||
185
app/model/wave_batch.js
Normal file
185
app/model/wave_batch.js
Normal file
@ -0,0 +1,185 @@
|
||||
// app/model/wave_batch.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, DATE, TINYINT, BOOLEAN } = app.Sequelize;
|
||||
|
||||
const WaveBatch = app.model.define('wms_wave_batch', {
|
||||
wave_id: {
|
||||
type: BIGINT,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '波次ID',
|
||||
},
|
||||
wave_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '波次编号,如WAVE202401001',
|
||||
},
|
||||
wave_type: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '波次类型:1-团购 2-散单',
|
||||
},
|
||||
wave_status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '波次状态:-1-已取消 0-自动加团中 1-已就绪 2-已打印 3-拣货中 4-拣货完成 5-复核完成 6-打包完成',
|
||||
},
|
||||
total_orders: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '总订单数',
|
||||
},
|
||||
processed_orders: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '已处理订单数',
|
||||
},
|
||||
picking_operator: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '拣货员',
|
||||
},
|
||||
picking_start_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '拣货开始时间',
|
||||
},
|
||||
picking_end_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '拣货结束时间',
|
||||
},
|
||||
print_operator: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '打印员',
|
||||
},
|
||||
print_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '打印时间',
|
||||
},
|
||||
print_count: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '打印次数',
|
||||
},
|
||||
check_operator: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '校验员',
|
||||
},
|
||||
check_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '校验时间',
|
||||
},
|
||||
check_result: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
comment: '校验结果',
|
||||
},
|
||||
priority: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: 5,
|
||||
comment: '优先级 1-5',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
creator: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '创建人',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
update_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '更新时间',
|
||||
},
|
||||
item_detail_machine: {
|
||||
type: STRING(1024),
|
||||
allowNull: true,
|
||||
comment: '抓取结构token:v1|item_part_type|item_part|distinguish_express|logistics_name|item_snapshot_key',
|
||||
},
|
||||
item_part_type: {
|
||||
type: STRING(32),
|
||||
allowNull: true,
|
||||
comment: '结构来源类型:items_hash/items',
|
||||
},
|
||||
item_part: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '结构主键(items_hash或items摘要)',
|
||||
},
|
||||
distinguish_express: {
|
||||
type: BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否区分快递 0否1是',
|
||||
},
|
||||
logistics_name: {
|
||||
type: STRING(128),
|
||||
allowNull: true,
|
||||
comment: '快递名称(区分快递时参与匹配)',
|
||||
},
|
||||
item_snapshot_key: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '结构快照键',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_wave_batch',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_wave_status',
|
||||
fields: [ 'wave_status', 'create_time' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_wave_no',
|
||||
fields: [ 'wave_no' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse',
|
||||
fields: [ 'warehouse_id', 'wave_status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_creator',
|
||||
fields: [ 'creator', 'create_time' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_wave_fast_group',
|
||||
fields: [ 'warehouse_id', 'wave_type', 'wave_status', 'item_part_type', 'item_part', 'distinguish_express', 'logistics_name' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_wave_snapshot_key',
|
||||
fields: [ 'item_snapshot_key' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_wave_item_machine_prefix',
|
||||
fields: [ { name: 'item_detail_machine', length: 191 } ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return WaveBatch;
|
||||
};
|
||||
@ -37,10 +37,8 @@ module.exports = app => {
|
||||
// 临时 fileWriter 消费入口
|
||||
router.get('/__temp/file-writer/consume', controller.tempFileWriter.consume);
|
||||
|
||||
// Polo API 测试入口
|
||||
router.get('/testPoloApi/:platid', controller.home.testPoloApi);
|
||||
router.get('/PoloApiGetWayBillCondition/:platid', controller.home.PoloApiGetWayBillCondition);
|
||||
|
||||
// 测试接口
|
||||
router.get('/testSendData', controller.home.testSendData);
|
||||
// IM交互入口
|
||||
router.post('/im', controller.im.index);
|
||||
};
|
||||
|
||||
171
app/service/im.js
Normal file
171
app/service/im.js
Normal file
@ -0,0 +1,171 @@
|
||||
'use strict';
|
||||
/**
|
||||
* IM 相关服务
|
||||
* @author 刘付明仁 2026-05-01 创建
|
||||
* 返回通用格式:{ code: number, message: string, data: any }
|
||||
* code: 200 表示成功,其他表示失败
|
||||
* message: 错误或成功消息
|
||||
* data: 具体数据内容,成功时通常包含请求结果,失败时可以为 null 或错误详情
|
||||
*/
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class ImService extends Service {
|
||||
async ping(data) {
|
||||
const { requestId } = data || {};
|
||||
return {
|
||||
code: 200,
|
||||
message: 'pong',
|
||||
data: {
|
||||
requestId,
|
||||
},
|
||||
};
|
||||
}
|
||||
async ssoCodeToId(data) {
|
||||
const { code } = data || {};
|
||||
const safeCode = String(code || '').trim();
|
||||
|
||||
if (!safeCode) {
|
||||
return {
|
||||
code: 400,
|
||||
message: 'code不能为空',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
// 测试例外,如果code以"test-"开头,则直接返回模拟数据
|
||||
if (safeCode.startsWith('test-')) {
|
||||
return {
|
||||
code: 200,
|
||||
message: 'success',
|
||||
data: {
|
||||
employees_id: 4,
|
||||
employees_name: '阿猫',
|
||||
subject: {
|
||||
id: 100000,
|
||||
name: '测试仓',
|
||||
type: 'warehouse',
|
||||
},
|
||||
avatar: '',
|
||||
},
|
||||
};
|
||||
}
|
||||
const cacheKey = `im:sso:code:${safeCode}`;
|
||||
const cachedUser = await this.app.getCacheAsync(cacheKey);
|
||||
|
||||
if (!cachedUser || !cachedUser.employees_id || !cachedUser.employees_name || !cachedUser.subject) {
|
||||
return {
|
||||
code: 404,
|
||||
message: 'code无效或已过期',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
await this.app.delCacheAsync(cacheKey);
|
||||
const resultData = {
|
||||
code: 200,
|
||||
message: 'success',
|
||||
data: {
|
||||
employees_id: cachedUser.employees_id,
|
||||
employees_name: cachedUser.employees_name,
|
||||
subject: cachedUser.subject,
|
||||
avatar: cachedUser.avatar,
|
||||
},
|
||||
};
|
||||
console.log('SSO code converted to user info:', resultData);
|
||||
return resultData;
|
||||
}
|
||||
/**
|
||||
* 获取主体员工信息
|
||||
* @param data
|
||||
*/
|
||||
async getStoreEmployees(data) {
|
||||
const { store_id } = data || {};
|
||||
const safeStoreId = Number(store_id);
|
||||
if (!safeStoreId) {
|
||||
return {
|
||||
code: 400,
|
||||
message: 'store_id不能为空或无效',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const store = await this.ctx.model.Store.findByPk(safeStoreId, {
|
||||
attributes: [ 'id', 'company_name', 'project' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!store) {
|
||||
return {
|
||||
code: 404,
|
||||
message: '主体不存在',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
const employees = await this.ctx.model.AccountStoreEmployee.findAll({
|
||||
where: {
|
||||
store_id: safeStoreId,
|
||||
status: 1,
|
||||
},
|
||||
attributes: [ 'id', 'real_name' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!employees || employees.length === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
message: 'success',
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
const employeeIds = employees.map(item => String(item.id));
|
||||
const avatarRefs = await this.ctx.model.FileReference.findAll({
|
||||
where: {
|
||||
business_type: 'avater',
|
||||
business_id: employeeIds,
|
||||
},
|
||||
include: [{
|
||||
model: this.ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
required: false,
|
||||
}],
|
||||
attributes: [ 'business_id', 'created_at' ],
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
});
|
||||
|
||||
const avatarMap = new Map();
|
||||
for (const ref of avatarRefs) {
|
||||
const employeeId = String(ref.business_id || '').trim();
|
||||
if (!employeeId || avatarMap.has(employeeId)) {
|
||||
continue;
|
||||
}
|
||||
avatarMap.set(employeeId, ref.file && ref.file.file_url ? ref.file.file_url : '');
|
||||
}
|
||||
|
||||
const subject = {
|
||||
id: String(store.id),
|
||||
name: String(store.company_name || ''),
|
||||
type: String(store.project || ''),
|
||||
};
|
||||
|
||||
const list = employees.map(item => {
|
||||
const employeeId = String(item.id);
|
||||
return {
|
||||
employees_id: employeeId,
|
||||
employees_name: String(item.real_name || ''),
|
||||
subject,
|
||||
avatar: avatarMap.get(employeeId) || '',
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: 'success',
|
||||
data: list,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ImService;
|
||||
@ -60,6 +60,13 @@ class pdaService extends Service {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存接口日志到系统日志模型
|
||||
* @param {Object} logData 日志数据
|
||||
* @param {number} startTime 开始时间戳
|
||||
* @returns {Promise<Object|undefined>} 写入结果
|
||||
*/
|
||||
async saveLog(logData, startTime) {
|
||||
const {
|
||||
ctx,
|
||||
@ -77,14 +84,17 @@ class pdaService extends Service {
|
||||
|
||||
logData.use_time = Date.now() - startTime;
|
||||
|
||||
// 使用 egg-mysql 保存日志到数据库
|
||||
const result = await ctx.app.mysql.get('wms').insert('wms_system_log', {
|
||||
// 使用 SystemLog model 保存日志到数据库
|
||||
if (!ctx.model || !ctx.model.SystemLog) {
|
||||
throw new Error('SystemLog model 不存在,无法写入系统日志');
|
||||
}
|
||||
const result = await ctx.model.SystemLog.create({
|
||||
method: logData.method || '',
|
||||
v: logData.v || '',
|
||||
url: logData.url || '',
|
||||
headers: logData.headers || '',
|
||||
auth: logData.auth || '',
|
||||
created_at: ctx.app.mysql.get('wms').literals.now,
|
||||
created_at: new Date(),
|
||||
body: logData.body || '',
|
||||
result: logData.result || '',
|
||||
use_time: logData.use_time || 0,
|
||||
|
||||
@ -156,6 +156,12 @@ class systemService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存接口日志到系统日志模型
|
||||
* @param {Object} logData 日志数据
|
||||
* @param {number} startTime 开始时间戳
|
||||
* @returns {Promise<Object|undefined>} 写入结果
|
||||
*/
|
||||
async saveLog(logData, startTime) {
|
||||
const {
|
||||
ctx,
|
||||
@ -173,14 +179,17 @@ class systemService extends Service {
|
||||
|
||||
logData.use_time = Date.now() - startTime;
|
||||
|
||||
// 使用 egg-mysql 保存日志到数据库
|
||||
const result = await ctx.app.mysql.get('wms').insert('wms_system_log', {
|
||||
// 使用 SystemLog model 保存日志到数据库
|
||||
if (!ctx.model || !ctx.model.SystemLog) {
|
||||
throw new Error('SystemLog model 不存在,无法写入系统日志');
|
||||
}
|
||||
const result = await ctx.model.SystemLog.create({
|
||||
method: logData.method || '',
|
||||
v: logData.v || '',
|
||||
url: logData.url || '',
|
||||
headers: logData.headers || '',
|
||||
auth: logData.auth || '',
|
||||
created_at: ctx.app.mysql.get('wms').literals.now,
|
||||
created_at: new Date(),
|
||||
body: logData.body || '',
|
||||
result: logData.result || '',
|
||||
use_time: logData.use_time || 0,
|
||||
|
||||
@ -11,31 +11,90 @@ class dashboardService extends MainService {
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog);
|
||||
}
|
||||
async storeStats() {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user?.store_id;
|
||||
|
||||
if (!warehouseId) {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const dispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId);
|
||||
const { Sequelize } = ctx.app;
|
||||
const { Op } = Sequelize;
|
||||
|
||||
// 待处理订单基础条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3)
|
||||
const pendingBase = {
|
||||
step: { [Op.in]: [ 1, 2, 3 ] },
|
||||
outbound_status: { [Op.ne]: 'padding' },
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
};
|
||||
|
||||
// 今日时间范围
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const todayEnd = new Date(todayStart.getTime() + 86400000);
|
||||
const yesterdayStart = new Date(todayStart.getTime() - 86400000);
|
||||
|
||||
const [
|
||||
totalPending,
|
||||
todayNew,
|
||||
yesterdayNew,
|
||||
unassignedOrders,
|
||||
unprintedOrders,
|
||||
unpickedOrders,
|
||||
pendingShipments,
|
||||
todayOutbound,
|
||||
interceptedOrders,
|
||||
exceptionOrders,
|
||||
] = await Promise.all([
|
||||
model.count({ where: pendingBase }),
|
||||
model.count({ where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }),
|
||||
model.count({ where: { ...pendingBase, create_at: { [Op.gte]: yesterdayStart, [Op.lt]: todayStart } } }),
|
||||
model.count({ where: { ...pendingBase, post_status: 'none' } }),
|
||||
model.count({ where: { ...pendingBase, print_status: 'none' } }),
|
||||
model.count({ where: { ...pendingBase, pick_status: 'none' } }),
|
||||
model.count({ where: { ...pendingBase, outbound_status: { [Op.ne]: 'fin' } } }),
|
||||
dispatchModel.count({ where: { dispatch_lane: 'm4', delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }),
|
||||
model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }),
|
||||
model.count({ where: { ...pendingBase, step: 3 } }),
|
||||
]);
|
||||
|
||||
const orderTrend = yesterdayNew > 0
|
||||
? parseFloat((((todayNew - yesterdayNew) / yesterdayNew) * 100).toFixed(1))
|
||||
: (todayNew > 0 ? 100 : 0);
|
||||
|
||||
const totalForRate = pendingShipments + todayOutbound;
|
||||
const outboundRate = totalForRate > 0
|
||||
? parseFloat(((todayOutbound / totalForRate) * 100).toFixed(2))
|
||||
: 0;
|
||||
|
||||
const shipmentProgress = totalPending > 0
|
||||
? parseFloat((((totalPending - pendingShipments) / totalPending) * 100).toFixed(0))
|
||||
: 0;
|
||||
|
||||
const data = {
|
||||
code: 200,
|
||||
message: '成功',
|
||||
data: {
|
||||
todayOrders: 13023,
|
||||
orderTrend: 2,
|
||||
todayOrders: totalPending,
|
||||
orderTrend,
|
||||
|
||||
// 处理状态
|
||||
unassignedOrders: 15, // 未分配快递号
|
||||
unprintedOrders: 32, // 未打印
|
||||
unpickedOrders: 28, // 未拣货
|
||||
unassignedOrders,
|
||||
unprintedOrders,
|
||||
unpickedOrders,
|
||||
|
||||
// 发货相关
|
||||
pendingShipments: 6542, // 待发货
|
||||
shipmentProgress: 0, // 发货进度
|
||||
pendingShipments,
|
||||
shipmentProgress,
|
||||
|
||||
// 出库相关
|
||||
todayOutbound: 6480, // 今日出库
|
||||
outboundRate: 49.77, // 出库完成率
|
||||
todayOutbound,
|
||||
outboundRate,
|
||||
|
||||
// 异常订单
|
||||
interceptedOrders: 8, // 拦截订单
|
||||
exceptionOrders: 10, // 异常订单
|
||||
interceptedOrders,
|
||||
exceptionOrders,
|
||||
},
|
||||
};
|
||||
|
||||
return this.success('ok', data);
|
||||
}
|
||||
async warehouseStats() {
|
||||
@ -145,174 +204,101 @@ class dashboardService extends MainService {
|
||||
return this.success('ok', data);
|
||||
}
|
||||
async express_ratio() {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user?.store_id;
|
||||
|
||||
if (!warehouseId) {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const { Sequelize } = ctx.app;
|
||||
|
||||
// 待处理订单条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3)
|
||||
// 排除已取消的订单
|
||||
const rows = await model.findAll({
|
||||
attributes: [
|
||||
'logistics_name',
|
||||
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ],
|
||||
],
|
||||
where: {
|
||||
step: { [Sequelize.Op.in]: [ 1, 2, 3 ] },
|
||||
outbound_status: { [Sequelize.Op.ne]: 'padding' },
|
||||
status: { [Sequelize.Op.ne]: 'cancel' },
|
||||
},
|
||||
group: [ 'logistics_name' ],
|
||||
order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 颜色调色板
|
||||
const colorPalette = [
|
||||
'#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A',
|
||||
'#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A',
|
||||
'#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7',
|
||||
];
|
||||
|
||||
const data = {
|
||||
code: 200,
|
||||
message: '成功',
|
||||
data: [{
|
||||
name: '顺丰速运',
|
||||
value: 50250,
|
||||
data: rows.map((row, index) => ({
|
||||
name: row.logistics_name || '未指定快递',
|
||||
value: Number(row.value),
|
||||
itemStyle: {
|
||||
color: '#409EFF',
|
||||
color: colorPalette[index % colorPalette.length],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '中通快递',
|
||||
value: 34089,
|
||||
itemStyle: {
|
||||
color: '#67C23A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '圆通速递',
|
||||
value: 10567,
|
||||
itemStyle: {
|
||||
color: '#E6A23C',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '韵达快递',
|
||||
value: 9023,
|
||||
itemStyle: {
|
||||
color: '#909399',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '申通快递',
|
||||
value: 8089,
|
||||
itemStyle: {
|
||||
color: '#67023A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '邮政EMS',
|
||||
value: 4089,
|
||||
itemStyle: {
|
||||
color: '#97293A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '京东物流',
|
||||
value: 3023,
|
||||
itemStyle: {
|
||||
color: '#F56C6C',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '极兔速递',
|
||||
value: 1089,
|
||||
itemStyle: {
|
||||
color: '#67913A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '德邦快递',
|
||||
value: 357,
|
||||
itemStyle: {
|
||||
color: '#9370DB',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '其他快递',
|
||||
value: 5,
|
||||
itemStyle: {
|
||||
color: '#67313A',
|
||||
},
|
||||
},
|
||||
],
|
||||
})),
|
||||
};
|
||||
|
||||
return this.success('ok', data);
|
||||
}
|
||||
async platform_distribution() {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user?.store_id;
|
||||
|
||||
if (!warehouseId) {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const { Sequelize } = ctx.app;
|
||||
|
||||
// 待处理订单条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3)
|
||||
// 排除已取消的订单
|
||||
const rows = await model.findAll({
|
||||
attributes: [
|
||||
'sys_platform_name',
|
||||
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ],
|
||||
],
|
||||
where: {
|
||||
step: { [Sequelize.Op.in]: [ 1, 2, 3 ] },
|
||||
outbound_status: { [Sequelize.Op.ne]: 'padding' },
|
||||
status: { [Sequelize.Op.ne]: 'cancel' },
|
||||
},
|
||||
group: [ 'sys_platform_name' ],
|
||||
order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 颜色调色板
|
||||
const colorPalette = [
|
||||
'#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A',
|
||||
'#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A',
|
||||
'#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7',
|
||||
];
|
||||
|
||||
const data = {
|
||||
code: 200,
|
||||
message: '成功',
|
||||
data: [{
|
||||
name: '抖音',
|
||||
value: 50250,
|
||||
data: rows.map((row, index) => ({
|
||||
name: row.sys_platform_name || '未指定平台',
|
||||
value: Number(row.value),
|
||||
itemStyle: {
|
||||
color: '#409EFF',
|
||||
color: colorPalette[index % colorPalette.length],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '拼多多',
|
||||
value: 34089,
|
||||
itemStyle: {
|
||||
color: '#67C23A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '小红书',
|
||||
value: 8089,
|
||||
itemStyle: {
|
||||
color: '#67023A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '淘宝',
|
||||
value: 10567,
|
||||
itemStyle: {
|
||||
color: '#E6A23C',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '快手',
|
||||
value: 9023,
|
||||
itemStyle: {
|
||||
color: '#909399',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '天猫',
|
||||
value: 4089,
|
||||
itemStyle: {
|
||||
color: '#97293A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '视频号',
|
||||
value: 3023,
|
||||
itemStyle: {
|
||||
color: '#606399',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '阿里巴巴',
|
||||
value: 1089,
|
||||
itemStyle: {
|
||||
color: '#67913A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '其他',
|
||||
value: 357,
|
||||
itemStyle: {
|
||||
color: '#9370DB',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'TITOK',
|
||||
value: 55,
|
||||
itemStyle: {
|
||||
color: '#17313A',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '京东',
|
||||
value: 45,
|
||||
itemStyle: {
|
||||
color: '#F56C6C',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: '德物',
|
||||
value: 5,
|
||||
itemStyle: {
|
||||
color: '#67313A',
|
||||
},
|
||||
},
|
||||
],
|
||||
})),
|
||||
};
|
||||
|
||||
return this.success('ok', data);
|
||||
}
|
||||
async order_trend() {
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
const { type } = require('os');
|
||||
const MainService = require('../main');
|
||||
const crypto = require('crypto');
|
||||
|
||||
class indexService extends MainService {
|
||||
/**
|
||||
@ -11,9 +13,9 @@ class indexService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect';
|
||||
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
async fastWhereTree(data) {
|
||||
@ -517,5 +519,55 @@ class indexService extends MainService {
|
||||
const result = await service.systems.platform.getPlatformList(isSystemOnly, isFull);
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
}
|
||||
/**
|
||||
* 前端请求生成唯一的登录码,后续可以通过这个登录码在IM系统中完成登录状态的绑定。登录码只写入到缓存中,不存储在数据库,具有较短的过期时间(如5分钟),并且只能使用一次。
|
||||
* @param {*} data
|
||||
*/
|
||||
async loginToIm() {
|
||||
const { ctx } = this;
|
||||
const { user } = ctx;
|
||||
if (!user || !user.id) {
|
||||
return this.fail('用户未登录', { code: 401 });
|
||||
}
|
||||
|
||||
const employeeId = String(user.employees_id ?? '').trim();
|
||||
const employeeName = String(user.employees_name ?? '').trim();
|
||||
const subjectId = String(user.store_id ?? '').trim();
|
||||
const subjectName = String(user.store_name ?? '').trim();
|
||||
const avatar = String(user.avatar ?? '').trim();
|
||||
const storeType = String(user.store_type ?? '').trim();
|
||||
|
||||
if (!employeeId || !employeeName || !subjectId || !subjectName || !storeType) {
|
||||
return this.fail('用户信息不完整', { code: 400 });
|
||||
}
|
||||
|
||||
const keyName = crypto.randomBytes(32).toString('hex');
|
||||
const cacheKey = `im:sso:code:${keyName}`;
|
||||
const payload = {
|
||||
employees_id: employeeId,
|
||||
employees_name: employeeName,
|
||||
subject: {
|
||||
id: subjectId,
|
||||
name: subjectName,
|
||||
type: storeType,
|
||||
},
|
||||
avatar,
|
||||
created_at: Date.now(),
|
||||
};
|
||||
|
||||
await this.app.setCacheAsync(cacheKey, payload, 300);
|
||||
|
||||
return this.success('ok', {
|
||||
data: {
|
||||
code: keyName,
|
||||
employees_id: employeeId,
|
||||
employees_name: employeeName,
|
||||
subject: payload.subject,
|
||||
store_type: storeType,
|
||||
avatar,
|
||||
},
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
}
|
||||
module.exports = indexService;
|
||||
|
||||
@ -38,9 +38,10 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([
|
||||
'sync_status',
|
||||
'items', 'items_count', 'items_total', 'items_weight',
|
||||
'wave_id',
|
||||
'wave_no',
|
||||
'post_status', 'storage_status', 'pick_status', 'pack_status',
|
||||
'inspection_status', 'print_status', 'claim_status',
|
||||
'outbound_status', 'lock_status', 'intercept_status','basket_number'
|
||||
'outbound_status', 'lock_status', 'intercept_status', 'basket_number',
|
||||
]);
|
||||
|
||||
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
|
||||
@ -181,6 +182,68 @@ class OrderBaseService extends MainService {
|
||||
return warehouseId === '' ? null : warehouseId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单日志使用的操作人信息。
|
||||
*
|
||||
* 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。
|
||||
*
|
||||
* @return {{ id: string|null, name: string }} 操作人信息。
|
||||
*/
|
||||
getOrderLogOperator() {
|
||||
const { ctx } = this;
|
||||
const stateUser = this.isPlainObject(ctx?.state?.user) ? ctx.state.user : null;
|
||||
const ctxUser = this.isPlainObject(ctx?.user) ? ctx.user : null;
|
||||
const paramsObject = this.isPlainObject(this.params) ? this.params : {};
|
||||
const paramsOperator = this.isPlainObject(paramsObject.__operator)
|
||||
? paramsObject.__operator
|
||||
: (this.isPlainObject(paramsObject.operator) ? paramsObject.operator : null);
|
||||
const operatorSource = stateUser || ctxUser || paramsOperator || {};
|
||||
|
||||
const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id;
|
||||
const rawOperatorName = operatorSource.employees_name
|
||||
?? operatorSource.operator_name
|
||||
?? operatorSource.real_name
|
||||
?? operatorSource.name;
|
||||
const operatorId = rawOperatorId === undefined || rawOperatorId === null
|
||||
? null
|
||||
: String(rawOperatorId).trim() || null;
|
||||
const operatorName = rawOperatorName === undefined || rawOperatorName === null
|
||||
? 'system'
|
||||
: String(rawOperatorName).trim() || 'system';
|
||||
|
||||
return {
|
||||
id: operatorId,
|
||||
name: operatorName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单日志使用的仓库ID。
|
||||
*
|
||||
* 取值优先级:显式传入参数 -> 当前上下文仓库 -> ctx.user.warehouse_id -> ctx.user.store_id。
|
||||
*
|
||||
* @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。
|
||||
* @return {number|string|null} 归一化后的仓库ID。
|
||||
*/
|
||||
getOrderLogWarehouseId(preferredWarehouseId = null) {
|
||||
const { ctx } = this;
|
||||
const candidates = [
|
||||
preferredWarehouseId,
|
||||
this.getWarehouseId(),
|
||||
ctx?.user?.warehouse_id,
|
||||
ctx?.user?.store_id,
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate === undefined || candidate === null || candidate === '') {
|
||||
continue;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范分页参数并限制 pageSize 上限。
|
||||
* @param {Object} pageParams 分页参数。
|
||||
|
||||
@ -33,6 +33,8 @@ class ExpectionOrderService extends OrderBaseService {
|
||||
async resolveException(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const operator = this.getOrderLogOperator();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
|
||||
if (!Array.isArray(requestData.ids) || requestData.ids.length === 0) {
|
||||
throw new Error('ids 不能为空');
|
||||
@ -61,14 +63,11 @@ class ExpectionOrderService extends OrderBaseService {
|
||||
try {
|
||||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: warehouseId,
|
||||
businessId: logWarehouseId,
|
||||
operationCode: 'ORDER_RESOLVE_EXCEPTION',
|
||||
operator: {
|
||||
id: this.ctx.user?.employees_id || this.ctx.user?.id,
|
||||
name: this.ctx.user?.employees_name || '',
|
||||
},
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId,
|
||||
warehouseId: logWarehouseId,
|
||||
orderIds,
|
||||
updated_count: count,
|
||||
message: `异常订单转正常:订单ID [${orderIds.join(', ')}],step 3 -> 2,共更新 ${count} 条`,
|
||||
|
||||
@ -3,12 +3,16 @@
|
||||
const OrderBaseService = require('./base');
|
||||
|
||||
class OrderIndexService extends OrderBaseService {
|
||||
/**
|
||||
* 初始化订单系统方法的免登录、免权限、免日志和免鉴权配置。
|
||||
* @param {Egg.Context} ctx 上下文对象。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail';
|
||||
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail';
|
||||
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,detail';
|
||||
const _noNeedRight = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail';
|
||||
const _noNeedLog = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail';
|
||||
const _noNeedAuth = 'list,badgeCount,manualOutboundOrder,queryOrderLogs,queryOrderLogList,detail';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -105,6 +109,54 @@ class OrderIndexService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单日志列表(不分页,返回全部)。
|
||||
*
|
||||
* 仅接受 order_id 及常见别名(id、orderId),
|
||||
* 仓库范围固定使用当前登录用户 store_id,避免越仓读取。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string|number} [data.order_id] 订单ID。
|
||||
* @param {string|number} [data.id] 订单ID别名。
|
||||
* @param {string|number} [data.orderId] 订单ID别名。
|
||||
* @return {Promise<Object>} 统一 success/fail 结构。
|
||||
*/
|
||||
async queryOrderLogList(data = {}) {
|
||||
const { service } = this;
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const {
|
||||
order_id: orderId,
|
||||
id,
|
||||
orderId: orderIdAlias,
|
||||
} = requestData;
|
||||
const rawOrderId = orderId ?? id ?? orderIdAlias;
|
||||
|
||||
if (rawOrderId === undefined || rawOrderId === null || String(rawOrderId).trim() === '') {
|
||||
return this.fail(`order_id 参数不能为空`, {}, 400);
|
||||
}
|
||||
|
||||
const normalizedOrderId = Number(String(rawOrderId).trim());
|
||||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||||
return this.fail(`order_id 参数不合法`, {}, 400);
|
||||
}
|
||||
|
||||
const warehouseId = this.getWarehouseId();
|
||||
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
|
||||
return this.fail(`缺少当前用户仓库上下文 store_id`, {}, 400);
|
||||
}
|
||||
|
||||
const logs = await service.systems.operationLog.queryAllOrderLogs({
|
||||
id: normalizedOrderId,
|
||||
warehouseId,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
list: logs,
|
||||
total: logs.length,
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = OrderIndexService;
|
||||
|
||||
@ -7,6 +7,16 @@ const PENDING_CANCEL_STATUS = 'cancel';
|
||||
const PENDING_CANCEL_STEP = 9;
|
||||
const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]);
|
||||
const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]);
|
||||
const ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_storage:request:';
|
||||
const ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
|
||||
const ALLOCATE_STORAGE_PROGRESS_MAP = Object.freeze({
|
||||
submitted: 5,
|
||||
running: 50,
|
||||
success: 100,
|
||||
failed: 100,
|
||||
not_found: 0,
|
||||
unknown: 0,
|
||||
});
|
||||
|
||||
class PendingOrderService extends OrderBaseService {
|
||||
/**
|
||||
@ -17,9 +27,9 @@ class PendingOrderService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel';
|
||||
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds';
|
||||
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel';
|
||||
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel';
|
||||
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds';
|
||||
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -32,6 +42,60 @@ class PendingOrderService extends OrderBaseService {
|
||||
return await this.listByModule('pendingOrder', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询待处理订单详情。
|
||||
*
|
||||
* 仅返回订单头、商品明细与运单信息;
|
||||
* 待处理详情不再返回 logs 字段,也不触发操作日志查询。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 订单头、商品明细和运单信息。
|
||||
*/
|
||||
async detail(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const orderIds = this.normalizeOrderIds(requestData);
|
||||
const tableType = this.resolveOrderTableType(requestData);
|
||||
|
||||
if (orderIds.length === 0) {
|
||||
throw new Error('订单ID不能为空');
|
||||
}
|
||||
|
||||
if (orderIds.length !== 1) {
|
||||
throw new Error('订单详情仅支持查询单个订单');
|
||||
}
|
||||
|
||||
const orderId = orderIds[0];
|
||||
const orderModel = await this.getOrderModelByTableType(tableType, warehouseId);
|
||||
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
|
||||
const order = await orderModel.findOne({
|
||||
where: orderWhere,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!order) {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId);
|
||||
const orderItems = await orderItemsModel.findAll({
|
||||
where: {
|
||||
order_id: orderId,
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems);
|
||||
const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId);
|
||||
const expresses = await this.getOrderExpressesByOrderId(orderId);
|
||||
|
||||
return {
|
||||
detail: order,
|
||||
items: orderItemsWithImages,
|
||||
expresses,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将待处理订单反审回待审核状态。
|
||||
* @param {Object} data 请求体。
|
||||
@ -48,7 +112,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
* 仓库上下文统一取当前登录用户的 store_id。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 统一 success 包装的储位分配结果。
|
||||
* @return {Promise<Object>} 统一 success 包装的受理结果,包含 request_id 与 warehouse_id。
|
||||
*/
|
||||
async allocateStorage(data = {}) {
|
||||
console.log('[PendingOrderService.allocateStorage] 原始入参', data);
|
||||
@ -78,19 +142,439 @@ class PendingOrderService extends OrderBaseService {
|
||||
};
|
||||
|
||||
console.log('[PendingOrderService.allocateStorage] 归一化入参', normalizedData);
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
const requestId = `storage_alloc_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`;
|
||||
const taskProgressState = {
|
||||
total_count: 0,
|
||||
processed_count: 0,
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
await this.setAllocateStorageTaskProgress(requestId, {
|
||||
status: 'submitted',
|
||||
total_count: taskProgressState.total_count,
|
||||
processed_count: taskProgressState.processed_count,
|
||||
progress: taskProgressState.progress,
|
||||
});
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setAllocateStorageTaskProgress(requestId, {
|
||||
status: 'running',
|
||||
total_count: taskProgressState.total_count,
|
||||
processed_count: taskProgressState.processed_count,
|
||||
progress: taskProgressState.progress,
|
||||
});
|
||||
|
||||
const allocationRequest = {
|
||||
allow_storage_location: normalizedData.allow_storage_location,
|
||||
order_ids: normalizedData.order_ids,
|
||||
progress_callback: async progressPayload => {
|
||||
const safeProgressPayload = this.isPlainObject(progressPayload) ? progressPayload : {};
|
||||
const totalCount = this.normalizeAllocateStorageTaskCount(
|
||||
safeProgressPayload.total_count
|
||||
?? safeProgressPayload.totalCount
|
||||
?? taskProgressState.total_count,
|
||||
taskProgressState.total_count
|
||||
);
|
||||
const processedCount = this.normalizeAllocateStorageTaskCount(
|
||||
safeProgressPayload.processed_count
|
||||
?? safeProgressPayload.processedCount
|
||||
?? taskProgressState.processed_count,
|
||||
taskProgressState.processed_count
|
||||
);
|
||||
|
||||
taskProgressState.total_count = Math.max(taskProgressState.total_count, totalCount);
|
||||
taskProgressState.processed_count = Math.min(
|
||||
taskProgressState.total_count,
|
||||
Math.max(taskProgressState.processed_count, processedCount)
|
||||
);
|
||||
taskProgressState.progress = this.normalizeAllocateStorageTaskProgress(
|
||||
safeProgressPayload.progress,
|
||||
'running',
|
||||
taskProgressState.total_count,
|
||||
taskProgressState.processed_count
|
||||
);
|
||||
|
||||
await this.setAllocateStorageTaskProgress(requestId, {
|
||||
status: 'running',
|
||||
total_count: taskProgressState.total_count,
|
||||
processed_count: taskProgressState.processed_count,
|
||||
progress: taskProgressState.progress,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
console.log('[PendingOrderService.allocateStorage] 后台开始处理储位分配', {
|
||||
request_id: requestId,
|
||||
allocationRequest: {
|
||||
allow_storage_location: allocationRequest.allow_storage_location,
|
||||
order_ids: allocationRequest.order_ids,
|
||||
},
|
||||
});
|
||||
const result = await this.service.systems.orderStorageAllocation.allocateStorage(allocationRequest);
|
||||
|
||||
if (taskProgressState.total_count > 0) {
|
||||
taskProgressState.processed_count = taskProgressState.total_count;
|
||||
}
|
||||
taskProgressState.progress = 100;
|
||||
|
||||
await this.setAllocateStorageTaskProgress(requestId, {
|
||||
status: 'success',
|
||||
total_count: taskProgressState.total_count,
|
||||
processed_count: taskProgressState.processed_count,
|
||||
progress: taskProgressState.progress,
|
||||
result,
|
||||
});
|
||||
|
||||
// 写操作日志(不影响主流程)
|
||||
try {
|
||||
const operator = this.getOrderLogOperator();
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
const orderIds = Array.isArray(normalizedData.order_ids)
|
||||
? normalizedData.order_ids
|
||||
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
|
||||
|
||||
// 从 result 中提取分配结果信息
|
||||
const resultData = result && result.data ? result.data : (result || {});
|
||||
const allocatedIds = Array.isArray(resultData.allocated_order_ids) ? resultData.allocated_order_ids : [];
|
||||
const shortageIds = Array.isArray(resultData.shortage_order_ids) ? resultData.shortage_order_ids : [];
|
||||
const allocatedSet = new Set(allocatedIds.map(Number));
|
||||
const shortageSet = new Set(shortageIds.map(Number));
|
||||
|
||||
if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||||
const operatorInfo = operator || {};
|
||||
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
|
||||
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
|
||||
const now = new Date();
|
||||
|
||||
const logRows = orderIds.map(orderId => {
|
||||
const oid = Number(orderId);
|
||||
const allocated = allocatedSet.has(oid);
|
||||
const shortage = shortageSet.has(oid);
|
||||
const operationCode = allocated
|
||||
? 'ORDER_STORAGE_ALLOCATE_SUCCESS'
|
||||
: shortage
|
||||
? 'ORDER_STORAGE_ALLOCATE_FAILED'
|
||||
: 'ORDER_STORAGE_ALLOCATE_SUCCESS';
|
||||
const msg = allocated
|
||||
? '储位分配成功'
|
||||
: shortage
|
||||
? '储位分配失败:库存不足'
|
||||
: '储位分配完成';
|
||||
return {
|
||||
business_type: 'order',
|
||||
business_id: String(oid),
|
||||
operation_code: operationCode,
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
external_log_type: 'NONE',
|
||||
warehouse_id: logWarehouseId || null,
|
||||
platform_code: 'SYSTEM',
|
||||
message: msg,
|
||||
created_at: now,
|
||||
};
|
||||
}).filter(row => Number(row.business_id) > 0);
|
||||
|
||||
if (logRows.length > 0) {
|
||||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||||
}
|
||||
}
|
||||
} catch (logErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入成功操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
console.log('[PendingOrderService.allocateStorage] 后台储位分配处理成功', {
|
||||
request_id: requestId,
|
||||
normalizedData,
|
||||
result,
|
||||
});
|
||||
} catch (error) {
|
||||
await this.setAllocateStorageTaskProgress(requestId, {
|
||||
status: 'failed',
|
||||
total_count: taskProgressState.total_count,
|
||||
processed_count: taskProgressState.processed_count,
|
||||
progress: taskProgressState.progress,
|
||||
error: error && error.message ? error.message : String(error),
|
||||
});
|
||||
|
||||
// 写操作日志(不影响主流程)
|
||||
try {
|
||||
const operator = this.getOrderLogOperator();
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
const orderIds = Array.isArray(normalizedData.order_ids)
|
||||
? normalizedData.order_ids
|
||||
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
|
||||
|
||||
if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||||
const operatorInfo = operator || {};
|
||||
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
|
||||
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
|
||||
const errorMsg = error && error.message ? error.message : String(error);
|
||||
const now = new Date();
|
||||
|
||||
const logRows = orderIds.map(orderId => {
|
||||
const oid = Number(orderId);
|
||||
return {
|
||||
business_type: 'order',
|
||||
business_id: String(oid),
|
||||
operation_code: 'ORDER_STORAGE_ALLOCATE_FAILED',
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
external_log_type: 'NONE',
|
||||
warehouse_id: logWarehouseId || null,
|
||||
platform_code: 'SYSTEM',
|
||||
message: `储位分配失败:${errorMsg}`,
|
||||
created_at: now,
|
||||
};
|
||||
}).filter(row => Number(row.business_id) > 0);
|
||||
|
||||
if (logRows.length > 0) {
|
||||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||||
}
|
||||
}
|
||||
} catch (logErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入失败操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
console.log('[PendingOrderService.allocateStorage] 后台储位分配处理异常', {
|
||||
request_id: requestId,
|
||||
normalizedData,
|
||||
error_message: error?.message,
|
||||
error_stack: error?.stack,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
request_id: requestId,
|
||||
warehouse_id: warehouseId,
|
||||
message: '请求已提交,后端处理中',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询待处理订单储位分配任务进度。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} data.request_id 请求ID(下划线写法)。
|
||||
* @param {string} data.requestId 请求ID(驼峰写法)。
|
||||
* @return {Promise<Object>} 统一响应,包含任务状态或结果。
|
||||
*/
|
||||
async allocateStorageProgress(data = {}) {
|
||||
const requestId = this.normalizeAllocateStorageRequestId(data);
|
||||
if (!requestId) {
|
||||
return this.fail('request_id 参数不能为空', {}, 400);
|
||||
}
|
||||
|
||||
const cachedProgress = await this.getAllocateStorageTaskProgress(requestId);
|
||||
if (!cachedProgress) {
|
||||
return this.success('ok', {
|
||||
request_id: requestId,
|
||||
status: 'not_found',
|
||||
progress: ALLOCATE_STORAGE_PROGRESS_MAP.not_found,
|
||||
total_count: 0,
|
||||
processed_count: 0,
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown';
|
||||
const normalizedCounts = this.normalizeAllocateStorageTaskCounts(cachedProgress, normalizedStatus);
|
||||
const normalizedProgress = this.normalizeAllocateStorageTaskProgress(
|
||||
cachedProgress.progress,
|
||||
normalizedStatus,
|
||||
normalizedCounts.total_count,
|
||||
normalizedCounts.processed_count
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
request_id: requestId,
|
||||
...cachedProgress,
|
||||
status: normalizedStatus,
|
||||
progress: normalizedProgress,
|
||||
total_count: normalizedCounts.total_count,
|
||||
processed_count: normalizedCounts.processed_count,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范任务进度值,兼容历史缓存中缺失 progress 字段的场景。
|
||||
*
|
||||
* @param {number|string|null|undefined} progress 原始进度值。
|
||||
* @param {string} status 任务状态。
|
||||
* @param {number} totalCount 总任务数。
|
||||
* @param {number} processedCount 已处理任务数。
|
||||
* @return {number} 归一化后的进度百分比(0-100)。
|
||||
*/
|
||||
normalizeAllocateStorageTaskProgress(progress, status = 'unknown', totalCount = 0, processedCount = 0) {
|
||||
const parsed = Number(progress);
|
||||
if (Number.isFinite(parsed)) {
|
||||
return Math.min(100, Math.max(0, Math.round(parsed)));
|
||||
}
|
||||
|
||||
if (String(status || 'unknown').trim() === 'success') {
|
||||
return 100;
|
||||
}
|
||||
|
||||
const normalizedTotalCount = this.normalizeAllocateStorageTaskCount(totalCount, 0);
|
||||
const normalizedProcessedCount = this.normalizeAllocateStorageTaskCount(processedCount, 0);
|
||||
if (normalizedTotalCount > 0) {
|
||||
return Math.round(Math.min(normalizedTotalCount, normalizedProcessedCount) / normalizedTotalCount * 100);
|
||||
}
|
||||
|
||||
const normalizedStatus = String(status || 'unknown').trim() || 'unknown';
|
||||
if (Object.prototype.hasOwnProperty.call(ALLOCATE_STORAGE_PROGRESS_MAP, normalizedStatus)) {
|
||||
return ALLOCATE_STORAGE_PROGRESS_MAP[normalizedStatus];
|
||||
}
|
||||
|
||||
return ALLOCATE_STORAGE_PROGRESS_MAP.unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范任务计数字段。
|
||||
*
|
||||
* @param {number|string|null|undefined} value 原始计数值。
|
||||
* @param {number} defaultValue 默认值。
|
||||
* @return {number} 归一化后的非负整数。
|
||||
*/
|
||||
normalizeAllocateStorageTaskCount(value, defaultValue = 0) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
return Math.max(0, Math.round(Number(defaultValue) || 0));
|
||||
}
|
||||
|
||||
return Math.max(0, Math.round(parsed));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范任务总量与处理量,兼容历史缓存与别名字段。
|
||||
*
|
||||
* @param {Object} payload 原始缓存载荷。
|
||||
* @param {string} status 任务状态。
|
||||
* @return {{ total_count: number, processed_count: number }} 归一化后的计数信息。
|
||||
*/
|
||||
normalizeAllocateStorageTaskCounts(payload = {}, status = 'unknown') {
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const totalCount = this.normalizeAllocateStorageTaskCount(
|
||||
safePayload.total_count
|
||||
?? safePayload.totalCount
|
||||
?? safePayload.total,
|
||||
0
|
||||
);
|
||||
let processedCount = this.normalizeAllocateStorageTaskCount(
|
||||
safePayload.processed_count
|
||||
?? safePayload.processedCount
|
||||
?? safePayload.processed,
|
||||
0
|
||||
);
|
||||
|
||||
if (totalCount > 0) {
|
||||
processedCount = Math.min(totalCount, processedCount);
|
||||
} else {
|
||||
processedCount = 0;
|
||||
}
|
||||
|
||||
if (String(status || 'unknown').trim() === 'success' && totalCount > 0) {
|
||||
processedCount = totalCount;
|
||||
}
|
||||
|
||||
return {
|
||||
total_count: totalCount,
|
||||
processed_count: processedCount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范待处理订单储位分配请求ID。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} data.request_id 请求ID(下划线写法)。
|
||||
* @param {string} data.requestId 请求ID(驼峰写法)。
|
||||
* @return {string} 归一化后的请求ID。
|
||||
*/
|
||||
normalizeAllocateStorageRequestId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.request_id || normalizedData.requestId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取待处理订单储位分配任务缓存键。
|
||||
*
|
||||
* @param {string} requestId 请求ID。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getAllocateStorageTaskCacheKey(requestId = '') {
|
||||
const normalizedRequestId = String(requestId || '').trim();
|
||||
if (!normalizedRequestId) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入待处理订单储位分配任务进度。
|
||||
*
|
||||
* @param {string} requestId 请求ID。
|
||||
* @param {Object} payload 任务状态与结果。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setAllocateStorageTaskProgress(requestId = '', payload = {}) {
|
||||
const cacheKey = this.getAllocateStorageTaskCacheKey(requestId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const normalizedStatus = String(safePayload.status || 'unknown').trim() || 'unknown';
|
||||
const normalizedCounts = this.normalizeAllocateStorageTaskCounts(safePayload, normalizedStatus);
|
||||
const normalizedProgress = this.normalizeAllocateStorageTaskProgress(
|
||||
safePayload.progress,
|
||||
normalizedStatus,
|
||||
normalizedCounts.total_count,
|
||||
normalizedCounts.processed_count
|
||||
);
|
||||
const progressPayload = {
|
||||
...safePayload,
|
||||
status: normalizedStatus,
|
||||
progress: normalizedProgress,
|
||||
total_count: normalizedCounts.total_count,
|
||||
processed_count: normalizedCounts.processed_count,
|
||||
request_id: String(requestId || '').trim(),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 前', normalizedData);
|
||||
const result = await this.service.systems.orderStorageAllocation.allocateStorage(normalizedData);
|
||||
console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 成功', result);
|
||||
|
||||
return this.success('ok', result);
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 异常', {
|
||||
normalizedData,
|
||||
error,
|
||||
});
|
||||
throw error;
|
||||
this.ctx.logger.warn('[pendingOrder.allocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取待处理订单储位分配任务进度。
|
||||
*
|
||||
* @param {string} requestId 请求ID。
|
||||
* @return {Promise<Object|null>} 任务缓存结果。
|
||||
*/
|
||||
async getAllocateStorageTaskProgress(requestId = '') {
|
||||
const cacheKey = this.getAllocateStorageTaskCacheKey(requestId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return cached;
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[pendingOrder.allocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@ -130,8 +614,81 @@ class PendingOrderService extends OrderBaseService {
|
||||
const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData);
|
||||
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 成功', result);
|
||||
|
||||
try {
|
||||
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||||
const operator = this.getOrderLogOperator() || {};
|
||||
const operatorId = operator.id != null ? String(operator.id) : null;
|
||||
const operatorName = operator.name ? String(operator.name) : 'system';
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
|
||||
const resultData = result && result.data ? result.data : {};
|
||||
const cancellableOrderIds = Array.isArray(resultData.cancellable_order_ids) ? resultData.cancellable_order_ids : [];
|
||||
const now = new Date();
|
||||
const logRows = [];
|
||||
|
||||
for (const orderId of cancellableOrderIds) {
|
||||
const normalizedOrderId = Number(orderId);
|
||||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
logRows.push({
|
||||
business_type: 'order',
|
||||
business_id: String(normalizedOrderId),
|
||||
operation_code: 'ORDER_STORAGE_UNALLOCATE_SUCCESS',
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
external_log_type: 'NONE',
|
||||
warehouse_id: logWarehouseId,
|
||||
platform_code: 'SYSTEM',
|
||||
message: '取消储位分配成功',
|
||||
created_at: now,
|
||||
});
|
||||
}
|
||||
|
||||
if (logRows.length > 0) {
|
||||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||||
}
|
||||
}
|
||||
} catch (logError) {
|
||||
this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配日志失败,不影响主流程', logError);
|
||||
}
|
||||
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
try {
|
||||
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||||
const rawOrderIds = Array.isArray(normalizedData.order_ids)
|
||||
? normalizedData.order_ids
|
||||
: (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []);
|
||||
const orderIds = [ ...new Set(rawOrderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)) ];
|
||||
|
||||
if (orderIds.length > 0) {
|
||||
const operator = this.getOrderLogOperator() || {};
|
||||
const operatorId = operator.id != null ? String(operator.id) : null;
|
||||
const operatorName = operator.name ? String(operator.name) : 'system';
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
|
||||
const errorMessage = error && error.message ? error.message : String(error);
|
||||
const now = new Date();
|
||||
const logRows = orderIds.map(orderId => ({
|
||||
business_type: 'order',
|
||||
business_id: String(orderId),
|
||||
operation_code: 'ORDER_STORAGE_UNALLOCATE_FAILED',
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
external_log_type: 'NONE',
|
||||
warehouse_id: logWarehouseId,
|
||||
platform_code: 'SYSTEM',
|
||||
message: `取消储位分配失败:${errorMessage}`,
|
||||
created_at: now,
|
||||
}));
|
||||
|
||||
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||||
}
|
||||
}
|
||||
} catch (logError) {
|
||||
this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配失败日志失败,不影响主流程', logError);
|
||||
}
|
||||
|
||||
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 异常', {
|
||||
normalizedData,
|
||||
error,
|
||||
@ -195,10 +752,44 @@ class PendingOrderService extends OrderBaseService {
|
||||
throw new Error('分配快递号接口仅支持订单对象数组入参');
|
||||
}
|
||||
|
||||
const { service } = this;
|
||||
const result = await service.systems.express.createWaybillCodePipeline(orders);
|
||||
const orderIds = [ ...new Set(
|
||||
orders
|
||||
.map(order => Number(order && (order.order_id || order.id)))
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||
) ];
|
||||
|
||||
return this.success('ok', result);
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.express.createWaybillCodePipeline(orders);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
try {
|
||||
const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
|
||||
if (orderIds.length > 0 && operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
const operator = this.getOrderLogOperator() || {};
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
|
||||
const errorMessage = error && error.message ? String(error.message) : String(error);
|
||||
|
||||
const payloads = orderIds.map(orderId => ({
|
||||
businessType: 'order',
|
||||
businessId: String(orderId),
|
||||
operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED',
|
||||
operator,
|
||||
extras: {
|
||||
message: `分配快递失败:${errorMessage}`,
|
||||
warehouseId: logWarehouseId,
|
||||
externalLogType: 'NONE',
|
||||
},
|
||||
}));
|
||||
|
||||
await operationLogService.createOperationLogs(payloads);
|
||||
}
|
||||
} catch (logError) {
|
||||
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 写入分配快递失败日志失败,不影响主流程', logError);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -339,6 +930,105 @@ class PendingOrderService extends OrderBaseService {
|
||||
throw new Error('订单不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
const ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0);
|
||||
if (ordersWithWave.length > 0) {
|
||||
try {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const WaveBatch = this.ctx.model.WaveBatch;
|
||||
|
||||
const waveOrderIds = ordersWithWave
|
||||
.map(order => Number(order.id))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||||
|
||||
if (waveOrderIds.length > 0) {
|
||||
await model.update(
|
||||
{
|
||||
wave_id: 0,
|
||||
wave_no: '',
|
||||
updated_at: now,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: waveOrderIds,
|
||||
},
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (WaveBatch) {
|
||||
const waveIdCountMap = new Map();
|
||||
for (const order of ordersWithWave) {
|
||||
const waveId = Number(order.wave_id);
|
||||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||||
continue;
|
||||
}
|
||||
waveIdCountMap.set(waveId, (waveIdCountMap.get(waveId) || 0) + 1);
|
||||
}
|
||||
|
||||
for (const [ waveId, canceledCount ] of waveIdCountMap.entries()) {
|
||||
await WaveBatch.decrement('total_orders', {
|
||||
by: canceledCount,
|
||||
where: {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
total_orders: {
|
||||
[Op.gt]: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wave = await WaveBatch.findOne({
|
||||
where: {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!wave) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const totalOrders = Number(wave.total_orders);
|
||||
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
|
||||
if (normalizedTotalOrders <= 0) {
|
||||
await WaveBatch.update(
|
||||
{
|
||||
total_orders: 0,
|
||||
wave_status: -1,
|
||||
update_time: now,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
}
|
||||
);
|
||||
} else {
|
||||
await WaveBatch.update(
|
||||
{
|
||||
update_time: now,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (waveErr) {
|
||||
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 清理波次关联失败,不影响订单取消', waveErr);
|
||||
}
|
||||
}
|
||||
|
||||
const updatedOrders = await model.findAll({
|
||||
where,
|
||||
raw: true,
|
||||
@ -472,6 +1162,8 @@ class PendingOrderService extends OrderBaseService {
|
||||
async updateOrderPlatform(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const operator = this.getOrderLogOperator();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
|
||||
const rawOrderIds = requestData.order_ids;
|
||||
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
|
||||
@ -515,14 +1207,11 @@ class PendingOrderService extends OrderBaseService {
|
||||
try {
|
||||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: warehouseId,
|
||||
businessId: logWarehouseId,
|
||||
operationCode: 'ORDER_UPDATE_PLATFORM',
|
||||
operator: {
|
||||
id: this.ctx.user?.employees_id || this.ctx.user?.id,
|
||||
name: this.ctx.user?.employees_name || '',
|
||||
},
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId,
|
||||
warehouseId: logWarehouseId,
|
||||
orderIds,
|
||||
sys_platform_code: platform.code,
|
||||
sys_platform_name: String(platform.name || '').trim(),
|
||||
@ -561,6 +1250,8 @@ class PendingOrderService extends OrderBaseService {
|
||||
async updateOrderExpress(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const operator = this.getOrderLogOperator();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
|
||||
const rawOrderIds = requestData.order_ids;
|
||||
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
|
||||
@ -628,14 +1319,11 @@ class PendingOrderService extends OrderBaseService {
|
||||
try {
|
||||
await this.ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: warehouseId,
|
||||
businessId: logWarehouseId,
|
||||
operationCode: 'ORDER_UPDATE_EXPRESS',
|
||||
operator: {
|
||||
id: this.ctx.user?.employees_id || this.ctx.user?.id,
|
||||
name: this.ctx.user?.employees_name || '',
|
||||
},
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId,
|
||||
warehouseId: logWarehouseId,
|
||||
orderIds,
|
||||
express_code: expressCode,
|
||||
sys_logistics_code: sysLogisticsCode,
|
||||
@ -677,6 +1365,8 @@ class PendingOrderService extends OrderBaseService {
|
||||
async cloneOrder(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const warehouseId = this.getWarehouseId();
|
||||
const operator = this.getOrderLogOperator();
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
|
||||
const orderId = Number(requestData.order_id || requestData.id);
|
||||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||||
@ -724,12 +1414,9 @@ class PendingOrderService extends OrderBaseService {
|
||||
businessType: 'order',
|
||||
businessId: orderId,
|
||||
operationCode: 'ORDER_CLONE_SOURCE',
|
||||
operator: {
|
||||
id: this.ctx.user?.employees_id || this.ctx.user?.id,
|
||||
name: this.ctx.user?.employees_name || '',
|
||||
},
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId,
|
||||
warehouseId: logWarehouseId,
|
||||
message: `订单克隆:原订单 ${orderId} 已取消,将创建新订单`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
@ -835,12 +1522,9 @@ class PendingOrderService extends OrderBaseService {
|
||||
businessType: 'order',
|
||||
businessId: newOrderId,
|
||||
operationCode: 'ORDER_CLONE_TARGET',
|
||||
operator: {
|
||||
id: this.ctx.user?.employees_id || this.ctx.user?.id,
|
||||
name: this.ctx.user?.employees_name || '',
|
||||
},
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId,
|
||||
warehouseId: logWarehouseId,
|
||||
message: `克隆创建:由原订单 ${orderId} 克隆生成,新订单 ID ${newOrderId}`,
|
||||
},
|
||||
beforeChanges: null,
|
||||
|
||||
58
app/service/systemMethods/order/print.js
Normal file
58
app/service/systemMethods/order/print.js
Normal file
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
const OrderBaseService = require('./base');
|
||||
|
||||
class OrderPrintService extends OrderBaseService {
|
||||
/**
|
||||
* 初始化订单打印模块的免登录、免权限、免日志和免鉴权配置。
|
||||
*
|
||||
* @param {Egg.Context} ctx 请求上下文。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getWavePrintData';
|
||||
const _noNeedLog = 'getWavePrintData';
|
||||
const _noNeedAuth = 'getWavePrintData';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取波次打印数据。
|
||||
*
|
||||
* method 层仅负责参数解构与边界校验,具体业务查询由 systems 层实现。
|
||||
* 返回结果中的 ext 会同时包含 missing_wave_ids 与 filtered_wave_ids。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<number|string>} data.wave_ids 波次ID数组。
|
||||
* @param {number|string} data.warehouse_id 仓库ID。
|
||||
* @return {Promise<Object>} 统一 success 包装的打印数据结果。
|
||||
*/
|
||||
async getWavePrintData(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const {
|
||||
wave_ids: waveIds,
|
||||
warehouse_id: warehouseId,
|
||||
} = requestData;
|
||||
|
||||
if (!Array.isArray(waveIds) || waveIds.length === 0) {
|
||||
throw new Error('wave_ids 必填,且必须为非空数组');
|
||||
}
|
||||
|
||||
if (warehouseId === undefined || warehouseId === null || String(warehouseId).trim() === '') {
|
||||
throw new Error('warehouse_id 必填');
|
||||
}
|
||||
|
||||
const result = await this.service.systems.orderPrint.getWavePrintData({
|
||||
waveIds,
|
||||
warehouseId,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: result,
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderPrintService;
|
||||
5550
app/service/systemMethods/order/wave.js
Normal file
5550
app/service/systemMethods/order/wave.js
Normal file
File diff suppressed because it is too large
Load Diff
172
app/service/systemMethods/pick.js
Normal file
172
app/service/systemMethods/pick.js
Normal file
@ -0,0 +1,172 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class PickService extends MainService {
|
||||
/**
|
||||
* 初始化 pick 模块鉴权配置。
|
||||
*
|
||||
* @param {Egg.Context} ctx 上下文对象。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'query';
|
||||
const _noNeedLog = 'query';
|
||||
const _noNeedAuth = 'query';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将入参标准化为布尔值。
|
||||
*
|
||||
* 兼容 `true/false`、`1/0`、`yes/no`、`on/off` 以及大小写字符串。
|
||||
*
|
||||
* @param {*} value 原始值。
|
||||
* @param {boolean} defaultValue 默认值。
|
||||
* @return {boolean} 解析后的布尔值。
|
||||
*/
|
||||
normalizeBoolean(value, defaultValue = false) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
|
||||
const normalized = String(value).trim().toLowerCase();
|
||||
if ([ '1', 'true', 'yes', 'y', 'on' ].includes(normalized)) {
|
||||
return true;
|
||||
}
|
||||
if ([ '0', 'false', 'no', 'n', 'off' ].includes(normalized)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按仓库上下文获取订单分表模型。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Object>} 订单模型。
|
||||
*/
|
||||
async getOrderModelByWarehouse(warehouseId) {
|
||||
const { ctx } = this;
|
||||
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||||
throw new Error('订单分表模型工厂不可用');
|
||||
}
|
||||
|
||||
const model = await factory.getCurrentModel(warehouseId);
|
||||
if (!model || typeof model.findOne !== 'function') {
|
||||
throw new Error('订单分表模型不可用');
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据快递号查询订单所在波次的拣货汇总信息。
|
||||
*
|
||||
* 入参:
|
||||
* - 快递号:`waybill_code`
|
||||
* - 完整显示开关:`full` / `full_display` / `is_full`
|
||||
*
|
||||
* 仓库上下文仅取当前登录用户 `ctx.user.store_id`(兼容 `ctx.state.user.store_id`),
|
||||
* 不依赖外部传入 `warehouse_id`,用于避免跨仓越界访问。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @return {Promise<Object>} 统一 success/fail 包装结果。
|
||||
*/
|
||||
async query(data = {}) {
|
||||
const { service, ctx } = this;
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const {
|
||||
waybill_code,
|
||||
full,
|
||||
full_display,
|
||||
is_full,
|
||||
} = requestData;
|
||||
|
||||
const normalizedWaybillCode = String(waybill_code || '').trim();
|
||||
if (!normalizedWaybillCode) {
|
||||
return this.fail('请传入快递号', {}, 400);
|
||||
}
|
||||
|
||||
const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined;
|
||||
const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined;
|
||||
const normalizedWarehouseId = Number(userWarehouseId || stateWarehouseId || 0);
|
||||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
return this.fail('缺少当前用户仓库上下文 store_id', {}, 400);
|
||||
}
|
||||
|
||||
const orderExpress = await ctx.model.OrderExpress.findOne({
|
||||
where: {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
waybill_code: normalizedWaybillCode,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderId = Number(orderExpress && orderExpress.order_id || 0);
|
||||
if (!orderExpress || orderId <= 0) {
|
||||
return this.fail('快递号不存在或不属于当前仓库', {}, 404);
|
||||
}
|
||||
|
||||
let orderModel = null;
|
||||
try {
|
||||
orderModel = await this.getOrderModelByWarehouse(normalizedWarehouseId);
|
||||
} catch (error) {
|
||||
return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500);
|
||||
}
|
||||
|
||||
const order = await orderModel.findOne({
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'store_id', 'wave_no', 'wave_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!order) {
|
||||
return this.fail('订单不存在', {}, 404);
|
||||
}
|
||||
|
||||
const waveNo = String(order.wave_no || '').trim();
|
||||
if (!waveNo) {
|
||||
return this.fail('订单未分配波次号,暂无拣货信息', {}, 400);
|
||||
}
|
||||
|
||||
const fullDisplay = this.normalizeBoolean(full ?? full_display ?? is_full, false);
|
||||
|
||||
try {
|
||||
const result = await service.systems.pick.queryPickingInfo({
|
||||
orderId,
|
||||
waveNo,
|
||||
waveId: Number(order.wave_id || 0),
|
||||
storeId: Number(order.store_id || 0),
|
||||
warehouseId: normalizedWarehouseId,
|
||||
fullDisplay,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: result,
|
||||
code: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
const code = Number(error && error.code);
|
||||
if (Number.isFinite(code) && code >= 400 && code < 600) {
|
||||
return this.fail(error.message || '查询失败', {}, code);
|
||||
}
|
||||
|
||||
ctx.logger.error('[PickService.query] 查询波次拣货信息失败: %s', error && error.message ? error.message : error);
|
||||
return this.fail('查询失败', {}, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PickService;
|
||||
83
app/service/systemMethods/setting/warehouse.js
Normal file
83
app/service/systemMethods/setting/warehouse.js
Normal file
@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
class SettingWarehouseMethodsService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库设置(subject_config)。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getSettings() {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.getSettings !== 'function') {
|
||||
return this.fail('获取仓库设置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await targetService.getSettings();
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取仓库设置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库设置字段元信息列表。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getFieldMeta() {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.getFieldMeta !== 'function') {
|
||||
return this.fail('获取仓库设置字段信息失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const list = targetService.getFieldMeta();
|
||||
return this.success('ok', { list });
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取仓库设置字段信息失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改仓库设置并清理指定仓库缓存。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async saveSettings(data = {}) {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.saveSettings !== 'function') {
|
||||
return this.fail('保存仓库设置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await targetService.saveSettings(data);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '保存仓库设置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingWarehouseMethodsService;
|
||||
@ -65,8 +65,12 @@ class WarehouseService extends MainService {
|
||||
*/
|
||||
async saveWarehouseStock(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.stockStore.saveWarehouseStock(data);
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
try {
|
||||
const result = await service.systems.stockStore.saveWarehouseStock(data);
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -146,19 +150,37 @@ class WarehouseService extends MainService {
|
||||
/**
|
||||
* 校验商品编码唯一性。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} [data.id] 商品ID(编辑场景)
|
||||
* @param {number} [data.item_id] 商品ID(编辑场景,排除自身)
|
||||
* @param {number} [data.id] 兼容旧字段的商品ID
|
||||
* @param {string} data.item_code 商品编码
|
||||
* @param {number} data.store_id 货主ID
|
||||
* @return {Promise<Object>} data 为布尔或冲突详情
|
||||
* @param {number} data.owner_id 货主ID
|
||||
* @param {number} [data.store_id] 兼容旧字段的货主ID
|
||||
* @param {number} data.warehouse_id 仓库ID
|
||||
* @return {Promise<Object>} data.unique 为是否唯一,重复时返回提示信息
|
||||
*/
|
||||
async checkItemCodeUnique(data) {
|
||||
const { ctx, service } = this;
|
||||
const { id, item_code, store_id } = data;
|
||||
const {
|
||||
item_id,
|
||||
id,
|
||||
item_code,
|
||||
owner_id,
|
||||
store_id,
|
||||
warehouse_id,
|
||||
} = data || {};
|
||||
const targetItemId = item_id || id || null;
|
||||
const targetOwnerId = owner_id || store_id;
|
||||
const targetWarehouseId = warehouse_id || ctx.user.store_id;
|
||||
try {
|
||||
if (!item_code || !store_id) {
|
||||
if (!item_code || !targetOwnerId || !targetWarehouseId) {
|
||||
return this.fail('参数错误');
|
||||
}
|
||||
const result = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id);
|
||||
const result = await service.systems.stockStore.checkItemCodeUnique(
|
||||
targetItemId,
|
||||
item_code,
|
||||
targetOwnerId,
|
||||
targetWarehouseId
|
||||
);
|
||||
return this.success('获取成功', { data: result, code: 200 });
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
|
||||
@ -236,10 +236,7 @@ class configService extends MainService {
|
||||
/**
|
||||
* 查询收货单操作日志(分页)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number|string} [data.id] 收货单ID
|
||||
* @param {number|string} [data.receiving_id] 收货单ID(兼容字段)
|
||||
* @param {number} [data.page] 页码
|
||||
* @param {number} [data.pageSize] 每页数量
|
||||
* @param {number|string} data.receiving_id 收货单ID
|
||||
* @param {Object} [data.pagination] 分页对象,支持 page/pageSize
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
@ -251,9 +248,9 @@ class configService extends MainService {
|
||||
: {};
|
||||
|
||||
const result = await service.systems.operationLog.queryReceivingLogs({
|
||||
id: requestData.id || requestData.receiving_id,
|
||||
page: requestData.page || pagination.page,
|
||||
pageSize: requestData.pageSize || pagination.pageSize || pagination.page_size,
|
||||
id: requestData.receiving_id,
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize || pagination.page_size,
|
||||
warehouseId: ctx.user.store_id,
|
||||
});
|
||||
|
||||
|
||||
@ -153,124 +153,6 @@ class RolePermissionService extends Service {
|
||||
.filter(item => Number.isFinite(item) && item > 0)));
|
||||
}
|
||||
|
||||
async getPermissionPathsForRoles(roleIds, options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const permissionIds = await this.getPermissionIdsForRoles(roleIds, {
|
||||
includeDisabled: options.includeDisabled === true,
|
||||
type: options.type || null,
|
||||
includeRoleDisabled: options.includeRoleDisabled === true,
|
||||
useLegacyFallback: options.useLegacyFallback !== false,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const where = {
|
||||
id: {
|
||||
[Op.in]: permissionIds,
|
||||
},
|
||||
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
|
||||
};
|
||||
|
||||
if (options.type) {
|
||||
where.type = options.type;
|
||||
}
|
||||
|
||||
if (options.typeLike) {
|
||||
where.type = {
|
||||
[Op.like]: options.typeLike,
|
||||
};
|
||||
}
|
||||
|
||||
if (options.typeNotLike) {
|
||||
where.type = {
|
||||
[Op.notLike]: options.typeNotLike,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = await ctx.model.Permission.findAll({
|
||||
where,
|
||||
attributes: [ 'path' ],
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
return Array.from(new Set(rows
|
||||
.map(item => item && item.path)
|
||||
.filter(Boolean)));
|
||||
}
|
||||
|
||||
async bulkAssign(roleId, permissionIds, options = {}) {
|
||||
const currentRole = await this.ctx.model.Role.findOne({
|
||||
where: { id: roleId },
|
||||
attributes: [ 'permissions' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
const currentState = this.normalizePermissionSet(currentRole && currentRole.permissions);
|
||||
const incomingState = this.normalizePermissionSet(permissionIds);
|
||||
const nextState = incomingState.allAccess || currentState.allAccess
|
||||
? '*'
|
||||
: [ ...currentState.permissionIds, ...incomingState.permissionIds ];
|
||||
|
||||
await this.assignPermissions(roleId, nextState, options);
|
||||
return this.toApiPermissionIds(nextState);
|
||||
}
|
||||
|
||||
async clearRolePermissions(roleId, options = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
return await ctx.model.Role.update({
|
||||
permissions: JSON.stringify([]),
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: roleId },
|
||||
transaction: options.transaction,
|
||||
});
|
||||
}
|
||||
|
||||
async getRolePermissions(roleId, includePermissionDetails = false) {
|
||||
const { ctx } = this;
|
||||
const permissionIds = await this.getPermissionIds(roleId);
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!includePermissionDetails) {
|
||||
return permissionIds.map(permissionId => ({
|
||||
role_id: Number(roleId),
|
||||
permission_id: Number(permissionId),
|
||||
}));
|
||||
}
|
||||
|
||||
const permissionRows = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: permissionIds,
|
||||
status: 1,
|
||||
},
|
||||
});
|
||||
const permissionMap = new Map(permissionRows.map(item => [ Number(item.id), item ]));
|
||||
|
||||
return permissionIds.map(permissionId => ({
|
||||
role_id: Number(roleId),
|
||||
permission_id: Number(permissionId),
|
||||
permission: permissionMap.get(Number(permissionId)) || null,
|
||||
}));
|
||||
}
|
||||
|
||||
async hasPermission(roleId, permissionId) {
|
||||
const permissionIds = await this.getPermissionIds(roleId, {
|
||||
includeDisabled: true,
|
||||
});
|
||||
|
||||
return permissionIds.includes(Number(permissionId));
|
||||
}
|
||||
|
||||
async assignPermissions(roleId, permissionIds, options = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
@ -285,33 +167,6 @@ class RolePermissionService extends Service {
|
||||
return true;
|
||||
}
|
||||
|
||||
async getPermissionTree(roleId, permissionType = null) {
|
||||
const { ctx } = this;
|
||||
const permissionIds = await this.getPermissionIds(roleId, {
|
||||
includeDisabled: false,
|
||||
type: permissionType,
|
||||
});
|
||||
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const permissions = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: permissionIds,
|
||||
status: 1,
|
||||
...(permissionType ? { type: permissionType } : {}),
|
||||
},
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
return ctx.model.Permission.buildPermissionTree(permissions);
|
||||
}
|
||||
|
||||
async getPermissionIds(roleId, options = {}) {
|
||||
return await this.getPermissionIdsForRoles([ roleId ], options);
|
||||
}
|
||||
|
||||
async removePermissionsFromAllRoles(permissionIds, options = {}) {
|
||||
const { ctx } = this;
|
||||
const removeSet = new Set((permissionIds || [])
|
||||
|
||||
@ -1770,6 +1770,7 @@ class UserService extends Service {
|
||||
let storeId = null;
|
||||
let storeName = null;
|
||||
let storeCode = null;
|
||||
let storeType = null;
|
||||
let roleName = null;
|
||||
let auth_end = null;
|
||||
let employees_name = null;
|
||||
@ -1779,6 +1780,7 @@ class UserService extends Service {
|
||||
storeId = currentRole.store_id;
|
||||
storeName = currentRole.store_name;
|
||||
storeCode = currentRole.store_code;
|
||||
storeType = currentRole.role_type;
|
||||
roleName = currentRole.role_name;
|
||||
employees_name = currentRole.real_name;
|
||||
auth_end = currentRole.auth_end;
|
||||
@ -1802,6 +1804,7 @@ class UserService extends Service {
|
||||
store_id: storeId,
|
||||
store_name: storeName,
|
||||
store_code: storeCode,
|
||||
store_type: storeType,
|
||||
menus,
|
||||
permissions,
|
||||
userRole,
|
||||
|
||||
@ -129,21 +129,89 @@ class DeliveryOrderService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将订单操作日志逐条写入数据库。
|
||||
* 获取订单日志使用的操作人信息。
|
||||
*
|
||||
* 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。
|
||||
*
|
||||
* @return {{ id: string|null, name: string }} 操作人信息。
|
||||
*/
|
||||
getOrderLogOperator() {
|
||||
const { ctx } = this;
|
||||
const stateUser = ctx && ctx.state && typeof ctx.state.user === 'object' && ctx.state.user
|
||||
? ctx.state.user
|
||||
: null;
|
||||
const ctxUser = ctx && ctx.user && typeof ctx.user === 'object'
|
||||
? ctx.user
|
||||
: null;
|
||||
const operatorSource = stateUser || ctxUser || {};
|
||||
|
||||
const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id;
|
||||
const rawOperatorName = operatorSource.employees_name
|
||||
?? operatorSource.operator_name
|
||||
?? operatorSource.real_name
|
||||
?? operatorSource.name;
|
||||
const operatorId = rawOperatorId === undefined || rawOperatorId === null
|
||||
? null
|
||||
: String(rawOperatorId).trim() || null;
|
||||
const operatorName = rawOperatorName === undefined || rawOperatorName === null
|
||||
? 'system'
|
||||
: String(rawOperatorName).trim() || 'system';
|
||||
|
||||
return {
|
||||
id: operatorId,
|
||||
name: operatorName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单日志使用的仓库ID。
|
||||
*
|
||||
* 取值优先级:显式传入参数 -> this.store.id -> ctx.user.warehouse_id -> ctx.user.store_id。
|
||||
*
|
||||
* @param {number|string|null} [preferredWarehouseId=null] 优先使用的仓库ID。
|
||||
* @return {number|string|null} 归一化后的仓库ID。
|
||||
*/
|
||||
getOrderLogWarehouseId(preferredWarehouseId = null) {
|
||||
const { ctx } = this;
|
||||
const candidates = [
|
||||
preferredWarehouseId,
|
||||
this.store && this.store.id,
|
||||
ctx && ctx.user && ctx.user.warehouse_id,
|
||||
ctx && ctx.user && ctx.user.store_id,
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate === undefined || candidate === null || candidate === '') {
|
||||
continue;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将订单操作日志写入数据库,优先批量写入。
|
||||
*
|
||||
* @param {Array<Object>} operationLogs 待写入的日志数组。
|
||||
* @param {number|string} orderId 订单ID。
|
||||
* @param {Object} [options={}] 写入选项。
|
||||
* @param {number|string} [options.warehouseId] 订单所属仓库ID。
|
||||
* @param {Object} [options.transaction] 事务对象(可选)。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async flushOrderOperationLogs(operationLogs, orderId) {
|
||||
async flushOrderOperationLogs(operationLogs, orderId, options = {}) {
|
||||
const { ctx } = this;
|
||||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
const requestOptions = options && typeof options === 'object' ? options : {};
|
||||
const operator = this.getOrderLogOperator();
|
||||
const warehouseId = this.getOrderLogWarehouseId(requestOptions.warehouseId ?? requestOptions.warehouse_id);
|
||||
|
||||
if (!Array.isArray(operationLogs) || operationLogs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!operationLogService || typeof operationLogService.createOperationLog !== 'function') {
|
||||
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') {
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] operationLog service unavailable', {
|
||||
orderId,
|
||||
logs: operationLogs.length,
|
||||
@ -151,32 +219,39 @@ class DeliveryOrderService extends Service {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const logItem of operationLogs) {
|
||||
try {
|
||||
const result = await operationLogService.createOperationLog({
|
||||
businessType: 'order',
|
||||
businessId: orderId,
|
||||
operationCode: logItem.operationCode,
|
||||
extras: {
|
||||
message: logItem.message,
|
||||
},
|
||||
});
|
||||
const payloads = operationLogs.map(logItem => ({
|
||||
businessType: 'order',
|
||||
businessId: orderId,
|
||||
operationCode: logItem.operationCode,
|
||||
operator,
|
||||
extras: {
|
||||
warehouseId,
|
||||
message: logItem.message,
|
||||
},
|
||||
transaction: requestOptions.transaction,
|
||||
}));
|
||||
|
||||
if (!result) {
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', {
|
||||
orderId,
|
||||
operationCode: logItem.operationCode,
|
||||
message: logItem.message,
|
||||
});
|
||||
try {
|
||||
const results = await operationLogService.createOperationLogs(payloads, {
|
||||
transaction: requestOptions.transaction,
|
||||
});
|
||||
|
||||
for (let index = 0; index < payloads.length; index += 1) {
|
||||
if (results[index]) {
|
||||
continue;
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志异常,不影响业务', {
|
||||
const logItem = operationLogs[index] || {};
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 写入操作日志失败,不影响业务', {
|
||||
orderId,
|
||||
operationCode: logItem.operationCode,
|
||||
message: logItem.message,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.warn('[DeliveryOrderService.flushOrderOperationLogs] 批量写入操作日志异常,不影响业务', {
|
||||
orderId,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -434,7 +509,7 @@ class DeliveryOrderService extends Service {
|
||||
*
|
||||
* @param {Object} data 奇门/系统订单入参。
|
||||
* @param {Object} info 当前仓库与货主上下文。
|
||||
* @param createChannel
|
||||
* @param {string} [createChannel=''] 订单创建渠道标识。
|
||||
* @return {Promise<Object>} 创建结果。
|
||||
*/
|
||||
async addOrder(data, info, createChannel = '') {
|
||||
@ -560,7 +635,9 @@ class DeliveryOrderService extends Service {
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
await this.flushOrderOperationLogs(operationLogs, orderId);
|
||||
await this.flushOrderOperationLogs(operationLogs, orderId, {
|
||||
warehouseId: info.warehouseId,
|
||||
});
|
||||
|
||||
// 异步处理:订单入队列
|
||||
await this.addOrderToQueue(orderId, info.warehouseId);
|
||||
@ -699,12 +776,91 @@ class DeliveryOrderService extends Service {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析订单操作人名称。
|
||||
*
|
||||
* 优先使用外部传入的操作人;当未传入时按创建渠道自动补齐:
|
||||
* - QM:奇门-${应用名称}
|
||||
* - API:API-${应用名称}
|
||||
* - MANUAL/其他:当前登录用户姓名(employees_name -> real_name -> name)
|
||||
*
|
||||
* @param {string|null|undefined} operatorName 外部传入的操作人名称。
|
||||
* @param {string} [createChannel='MANUAL'] 订单创建渠道标识。
|
||||
* @param {Object} [info={}] 当前仓库与货主上下文。
|
||||
* @return {Promise<string|null>} 解析后的操作人名称。
|
||||
*/
|
||||
async resolveOperatorName(operatorName, createChannel = 'MANUAL', info = {}) {
|
||||
const explicitOperatorName = operatorName === undefined || operatorName === null
|
||||
? ''
|
||||
: String(operatorName).trim();
|
||||
if (explicitOperatorName) {
|
||||
return explicitOperatorName;
|
||||
}
|
||||
|
||||
const normalizedCreateChannel = String(createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL';
|
||||
const appKey = String(
|
||||
(info && info.appKey)
|
||||
|| (this.ctx.user && this.ctx.user.app_key)
|
||||
|| ''
|
||||
).trim();
|
||||
|
||||
if (normalizedCreateChannel === 'QM') {
|
||||
if (!appKey) {
|
||||
return '奇门';
|
||||
}
|
||||
|
||||
try {
|
||||
const app = await this.ctx.model.QimenApp.findOne({
|
||||
where: { app_key: appKey },
|
||||
attributes: [ 'name' ],
|
||||
raw: true,
|
||||
});
|
||||
const appName = String(app && app.name || '').trim();
|
||||
return appName ? `奇门-${appName}` : '奇门';
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询奇门应用失败,不影响主流程: %s', error.message);
|
||||
return '奇门';
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedCreateChannel === 'API') {
|
||||
if (!appKey) {
|
||||
return 'API';
|
||||
}
|
||||
|
||||
try {
|
||||
const app = await this.ctx.model.ApiApp.findOne({
|
||||
where: { self_app_key: appKey },
|
||||
attributes: [ 'app_name' ],
|
||||
raw: true,
|
||||
});
|
||||
const appName = String(app && app.app_name || '').trim();
|
||||
return appName ? `API-${appName}` : 'API';
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[DeliveryOrderService.resolveOperatorName] 查询API应用失败,不影响主流程: %s', error.message);
|
||||
return 'API';
|
||||
}
|
||||
}
|
||||
|
||||
const loginUser = this.ctx.user && typeof this.ctx.user === 'object'
|
||||
? this.ctx.user
|
||||
: (this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object' ? this.ctx.state.user : {});
|
||||
const manualOperatorName = String(
|
||||
loginUser.employees_name
|
||||
|| loginUser.real_name
|
||||
|| loginUser.name
|
||||
|| ''
|
||||
).trim();
|
||||
|
||||
return manualOperatorName || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 准备订单主表数据。
|
||||
*
|
||||
* @param {Object} deliveryOrder 订单主信息。
|
||||
* @param {Object} info 当前仓库与货主上下文。
|
||||
* @param createChannel
|
||||
* @param {string} [createChannel='MANUAL'] 订单创建渠道标识。
|
||||
* @param {number} step 订单步骤。
|
||||
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
|
||||
* @return {Promise<Object>} 可入库的订单数据。
|
||||
@ -760,6 +916,7 @@ class DeliveryOrderService extends Service {
|
||||
warehouseId: info.warehouseId,
|
||||
storeId: info.storeId,
|
||||
}, operationLogs);
|
||||
const resolvedOperatorName = await this.resolveOperatorName(operatorName, createChannel, info);
|
||||
|
||||
return {
|
||||
delivery_order_code: deliveryOrderCode,
|
||||
@ -780,7 +937,7 @@ class DeliveryOrderService extends Service {
|
||||
shop_nick: shopNick,
|
||||
seller_nick: sellerNick,
|
||||
buyer_nick: buyerNick,
|
||||
operator_name: operatorName,
|
||||
operator_name: resolvedOperatorName,
|
||||
operate_time: operateTime ? new Date(operateTime) : null,
|
||||
total_amount: totalAmount ? parseFloat(totalAmount) : 0,
|
||||
item_amount: itemAmount ? parseFloat(itemAmount) : 0,
|
||||
@ -963,9 +1120,7 @@ class DeliveryOrderService extends Service {
|
||||
const sortedStocks = Array.from(stockQuantityMap.entries())
|
||||
.sort(([ stockIdA ], [ stockIdB ]) => stockIdA - stockIdB)
|
||||
.map(([ stockId, quantity ]) => {
|
||||
// 可选:在字符串中包含重量信息
|
||||
const weight = stockWeightMap.get(stockId) || 0;
|
||||
return `${stockId}+${quantity}${weight > 0 ? `@${weight}` : ''}`;
|
||||
return `${stockId}+${quantity}`;
|
||||
});
|
||||
items_str = sortedStocks.join('|');
|
||||
|
||||
|
||||
@ -93,6 +93,135 @@ class ExpressService extends Service {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建快递号分配链路追踪ID。
|
||||
*
|
||||
* 优先使用入参中的 trace_id/traceId,其次读取上下文 trace 信息,最后兜底生成。
|
||||
*
|
||||
* @param {Object} [data={}] 入参。
|
||||
* @param {string} [fallback=''] 兜底标识。
|
||||
* @return {string} 追踪ID。
|
||||
*/
|
||||
buildWaybillTraceId(data = {}, fallback = '') {
|
||||
const normalizedData = data && typeof data === 'object' ? data : {};
|
||||
const ctxTraceId = this.ctx && this.ctx.traceId !== undefined
|
||||
? this.ctx.traceId
|
||||
: this.ctx && this.ctx.requestId !== undefined
|
||||
? this.ctx.requestId
|
||||
: this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined
|
||||
? this.ctx.state.traceId
|
||||
: '';
|
||||
const normalizedTraceId = String(
|
||||
normalizedData.trace_id
|
||||
|| normalizedData.traceId
|
||||
|| ctxTraceId
|
||||
|| fallback
|
||||
|| ''
|
||||
).trim();
|
||||
|
||||
if (normalizedTraceId) {
|
||||
return normalizedTraceId;
|
||||
}
|
||||
|
||||
return `waybill_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单日志使用的操作人信息。
|
||||
*
|
||||
* 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。
|
||||
*
|
||||
* @return {{ id: string|null, name: string }} 操作人信息。
|
||||
*/
|
||||
getOrderLogOperator() {
|
||||
const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object'
|
||||
? this.ctx.state.user
|
||||
: null;
|
||||
const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object'
|
||||
? this.ctx.user
|
||||
: null;
|
||||
const operatorSource = stateUser || ctxUser || {};
|
||||
|
||||
const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id;
|
||||
const rawOperatorName = operatorSource.employees_name
|
||||
?? operatorSource.operator_name
|
||||
?? operatorSource.real_name
|
||||
?? operatorSource.name;
|
||||
const operatorId = rawOperatorId === undefined || rawOperatorId === null
|
||||
? null
|
||||
: String(rawOperatorId).trim() || null;
|
||||
const operatorName = rawOperatorName === undefined || rawOperatorName === null
|
||||
? 'system'
|
||||
: String(rawOperatorName).trim() || 'system';
|
||||
|
||||
return {
|
||||
id: operatorId,
|
||||
name: operatorName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单日志使用的仓库ID。
|
||||
*
|
||||
* @param {number|string|null} [preferredWarehouseId=null] 优先仓库ID。
|
||||
* @return {number|string|null} 仓库ID。
|
||||
*/
|
||||
getOrderLogWarehouseId(preferredWarehouseId = null) {
|
||||
const candidates = [
|
||||
preferredWarehouseId,
|
||||
this.getCurrentWarehouseId(),
|
||||
this.ctx && this.ctx.user ? this.ctx.user.warehouse_id : null,
|
||||
this.ctx && this.ctx.user ? this.ctx.user.store_id : null,
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate === undefined || candidate === null || candidate === '') {
|
||||
continue;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为分配快递失败订单写入订单操作日志。
|
||||
*
|
||||
* @param {Array<number|string>} orderIds 订单ID数组。
|
||||
* @param {string} errorMessage 失败原因。
|
||||
* @param {number|string|null} warehouseId 仓库ID。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async createAllocateExpressFailureLogs(orderIds = [], errorMessage = '', warehouseId = null) {
|
||||
const operationLogService = this.service
|
||||
&& this.service.systems
|
||||
&& this.service.systems.operationLog;
|
||||
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const operator = this.getOrderLogOperator();
|
||||
const normalizedWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
|
||||
.map(orderId => Number(orderId))
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
|
||||
const normalizedErrorMessage = String(errorMessage || '').trim() || '未知异常';
|
||||
|
||||
const payloads = normalizedOrderIds.map(orderId => ({
|
||||
businessType: 'order',
|
||||
businessId: String(orderId),
|
||||
operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED',
|
||||
operator,
|
||||
extras: {
|
||||
message: `分配快递失败:${normalizedErrorMessage}`,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
externalLogType: 'API',
|
||||
},
|
||||
}));
|
||||
|
||||
await operationLogService.createOperationLogs(payloads);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 business_key 规范化为内部可处理的正整数列表。
|
||||
*【已使用】
|
||||
@ -223,10 +352,9 @@ class ExpressService extends Service {
|
||||
*/
|
||||
async normalizeWaybillCreateOrders(orders = []) {
|
||||
const normalizedOrders = Array.isArray(orders) ? orders : [];
|
||||
console.log('normalizeWaybillCreateOrders 原始订单列表', normalizedOrders);
|
||||
const normalizedOrderMap = new Map();
|
||||
|
||||
const ExpressList = await this.loadExpressList();
|
||||
await this.loadExpressList();
|
||||
for (const order of normalizedOrders) {
|
||||
if (!order || typeof order !== 'object') {
|
||||
continue;
|
||||
@ -234,7 +362,6 @@ class ExpressService extends Service {
|
||||
|
||||
const orderId = Number(order.id || order.order_id);
|
||||
const businessKeys = this.normalizeWaybillBusinessKeys(order.business_key);
|
||||
console.log('businessKeys', businessKeys);
|
||||
if (!Number.isInteger(orderId) || orderId <= 0 || businessKeys.length === 0) {
|
||||
continue;
|
||||
}
|
||||
@ -242,7 +369,6 @@ class ExpressService extends Service {
|
||||
const sysPlatformCode = String(order.sys_platform_code || order.sysPlatformCode || '').trim();
|
||||
const logisticsCode = String(order.logistics_code || order.logisticsCode || '').trim();
|
||||
const syslogisticsCode = String(order.sys_logistics_code || order.sysLogisticsCode || '').trim();
|
||||
console.log('syslogisticsCode', syslogisticsCode);
|
||||
const platformCode = this.normalizeWaybillCreatePlatformCode(order);
|
||||
|
||||
for (const businessKey of businessKeys) {
|
||||
@ -1336,9 +1462,7 @@ class ExpressService extends Service {
|
||||
if (typeof dispatchMethod !== 'function') {
|
||||
throw new Error(normalizedPlatformCode + '接口未实现');
|
||||
}
|
||||
// console.log("业务数据骨架", JSON.stringify(bizcontent));
|
||||
const dispatchResult = await dispatchMethod.call(expressPlatformService, bizcontent);
|
||||
// console.log("平台接口返回结果", JSON.stringify(dispatchResult));
|
||||
if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') {
|
||||
throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败');
|
||||
}
|
||||
@ -1434,12 +1558,10 @@ class ExpressService extends Service {
|
||||
* 【已使用】
|
||||
*/
|
||||
async getWaybillAsyncOrderDeliveryModel(currentWarehouseId = 0) {
|
||||
console.log('=======================================');
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!currentWarehouseId || !orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
|
||||
return null;
|
||||
}
|
||||
console.log('getWaybillAsyncOrderDeliveryModel 当前仓库ID', currentWarehouseId);
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId);
|
||||
if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') {
|
||||
return null;
|
||||
@ -1463,14 +1585,27 @@ class ExpressService extends Service {
|
||||
const { app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const orderList = Array.isArray(orders) ? orders : [];
|
||||
const traceId = this.buildWaybillTraceId({}, `pipeline_${Date.now()}`);
|
||||
|
||||
console.log('createWaybillCodePipeline 输入订单列表', orderList);
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 入口请求', {
|
||||
traceId,
|
||||
orderCount: orderList.length,
|
||||
orderIds: orderList.slice(0, 50).map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0),
|
||||
waveIds: orderList.slice(0, 50).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0),
|
||||
});
|
||||
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
const orderDeliveryModel = await this.getWaybillAsyncOrderDeliveryModel(warehouseId);
|
||||
|
||||
console.log('orderDeliveryModel', orderDeliveryModel);
|
||||
if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') {
|
||||
this.ctx.logger.error('[ExpressService.createWaybillCodePipeline] 分配前置条件失败-订单主表模型不可用', {
|
||||
traceId,
|
||||
warehouseId,
|
||||
});
|
||||
throw new Error('订单主表模型未初始化');
|
||||
}
|
||||
|
||||
// 【step1】先按订单ID和业务键筛选 wms_order_express,找出已存在的快递记录,避免重复创建。
|
||||
const orders_arr = await orderDeliveryModel.findAll({
|
||||
where: {
|
||||
@ -1483,7 +1618,12 @@ class ExpressService extends Service {
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ],
|
||||
raw: true,
|
||||
});
|
||||
console.log('createWaybillCodePipeline 查询订单主表结果', orders_arr);
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 订单筛选结果', {
|
||||
traceId,
|
||||
warehouseId,
|
||||
inputOrderCount: orderList.length,
|
||||
matchedOrderCount: Array.isArray(orders_arr) ? orders_arr.length : 0,
|
||||
});
|
||||
// orders_arr和orderList合并
|
||||
const ordersWithExpress = orders_arr.map(order => {
|
||||
const matchedExpress = orderList.find(express => Number(order.id) === Number(express.order_id));
|
||||
@ -1492,25 +1632,34 @@ class ExpressService extends Service {
|
||||
business_key: matchedExpress ? matchedExpress.business_key : 1,
|
||||
};
|
||||
});
|
||||
console.log('createWaybillCodePipeline 订单列表与快递信息合并结果', ordersWithExpress);
|
||||
const groupedOrders = this.groupWaybillOrdersByPlatformAndLogistics(ordersWithExpress);
|
||||
|
||||
console.log('createWaybillCodePipeline 按平台和物流分组结果', groupedOrders);
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 平台物流分组结果', {
|
||||
traceId,
|
||||
groupedCount: groupedOrders.length,
|
||||
});
|
||||
|
||||
// 【step2】按平台 + 快递编码分组,后续按组串行处理。
|
||||
const platformList = await this.service.systems.platform.getPlatformList(true, true);
|
||||
console.log('createWaybillCodePipeline 平台列表', platformList);
|
||||
for (const groupedOrder of groupedOrders) {
|
||||
const matchedPlatform = platformList.find(platform => String(platform.code || '').trim().toLowerCase() === String(groupedOrder.options.sys_platform_code || '').trim().toLowerCase());
|
||||
const batches = this.splitWaybillOrdersIntoBatches(groupedOrder.orders);
|
||||
const listByWarehousePlatformCode = await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({ warehouseId, platform_code: groupedOrder.options.sys_platform_code });
|
||||
console.log('createWaybillCodePipeline 按批次切分结果', batches, 'expressInterfaceList', listByWarehousePlatformCode, 'matchedPlatform', matchedPlatform);
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 分组前置条件检查', {
|
||||
traceId,
|
||||
warehouseId,
|
||||
storeId: groupedOrder.options.store_id || 0,
|
||||
sysPlatformCode: groupedOrder.options.sys_platform_code,
|
||||
logisticsCode: groupedOrder.options.logistics_code,
|
||||
matchedPlatformCode: matchedPlatform && matchedPlatform.code,
|
||||
hasExpressInterface: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.data && listByWarehousePlatformCode.data[0]),
|
||||
});
|
||||
// 先获取货主配置货主是否配置了发件人,如果没有再使用快递接口的发件人信息。发件人信息在 listByWarehousePlatformCode.data[0] 中。
|
||||
const storeInfo = await this.service.systems.storeWarehouse.getContractConfig(warehouseId, groupedOrder.options.store_id);
|
||||
const expressInterface = listByWarehousePlatformCode.data[0];
|
||||
const storeConfig = storeInfo ? storeInfo.policy_config : null;
|
||||
const useStoreSenderInfoValue = storeConfig ? storeConfig.use_store_sender_info : 1;
|
||||
const shouldUseStoreSenderInfo = Number(useStoreSenderInfoValue === undefined || useStoreSenderInfoValue === null || useStoreSenderInfoValue === '' ? 1 : useStoreSenderInfoValue) === 1;
|
||||
console.log('storeInfo', storeInfo, expressInterface);
|
||||
const expressInterfaceConfig = expressInterface ? {
|
||||
...expressInterface,
|
||||
...(shouldUseStoreSenderInfo ? {
|
||||
@ -1524,12 +1673,19 @@ class ExpressService extends Service {
|
||||
address: (storeConfig && storeConfig.address) || expressInterface.address || '',
|
||||
} : {}),
|
||||
} : null;
|
||||
console.log('expressInterfaceConfig', expressInterfaceConfig);
|
||||
for (const batch of batches) {
|
||||
// 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。
|
||||
this.asyncTask(batch, groupedOrder.options, matchedPlatform, expressInterfaceConfig);
|
||||
this.asyncTask(batch, {
|
||||
...groupedOrder.options,
|
||||
trace_id: traceId,
|
||||
warehouse_id: warehouseId,
|
||||
}, matchedPlatform, expressInterfaceConfig);
|
||||
}
|
||||
}
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCodePipeline] 流水线任务提交完成', {
|
||||
traceId,
|
||||
groupedCount: groupedOrders.length,
|
||||
});
|
||||
return { message: '分配快递任务已提交' };
|
||||
}
|
||||
/**
|
||||
@ -1543,30 +1699,70 @@ class ExpressService extends Service {
|
||||
*/
|
||||
|
||||
async asyncTask(batch, options, matchedPlatform, listByWarehousePlatformCode) {
|
||||
console.log('asyncTask 输入参数 batch', batch, 'options', options, 'matchedPlatform', matchedPlatform, 'listByWarehousePlatformCode', listByWarehousePlatformCode);
|
||||
const traceId = this.buildWaybillTraceId(options || {}, 'asyncTask');
|
||||
this.ctx.logger.info('[ExpressService.asyncTask] 任务入口', {
|
||||
traceId,
|
||||
warehouseId: options && options.warehouse_id,
|
||||
sysPlatformCode: options && options.sys_platform_code,
|
||||
logisticsCode: options && options.logistics_code,
|
||||
orderIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0),
|
||||
waveIds: (Array.isArray(batch) ? batch : []).map(order => Number(order && order.wave_id)).filter(waveId => Number.isFinite(waveId) && waveId > 0),
|
||||
});
|
||||
try {
|
||||
if (!listByWarehousePlatformCode) {
|
||||
this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-快递接口配置缺失', {
|
||||
traceId,
|
||||
sysPlatformCode: options && options.sys_platform_code,
|
||||
logisticsCode: options && options.logistics_code,
|
||||
});
|
||||
throw new Error(`当前订单平台【${options.sys_platform_name}】,快递【${options.logistics_name}】,未配置有效的快递接口`);
|
||||
}
|
||||
if (!matchedPlatform) {
|
||||
this.ctx.logger.warn('[ExpressService.asyncTask] 分配前置条件失败-平台配置缺失', {
|
||||
traceId,
|
||||
sysPlatformCode: options && options.sys_platform_code,
|
||||
logisticsCode: options && options.logistics_code,
|
||||
});
|
||||
throw new Error(`未找到订单平台【${options.sys_platform_name}】的有效平台配置`);
|
||||
}
|
||||
await this.createWaybillCode(batch, matchedPlatform, listByWarehousePlatformCode);
|
||||
this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 前', {
|
||||
traceId,
|
||||
batchCount: Array.isArray(batch) ? batch.length : 0,
|
||||
});
|
||||
await this.createWaybillCode(batch, matchedPlatform, {
|
||||
...(listByWarehousePlatformCode || {}),
|
||||
trace_id: traceId,
|
||||
});
|
||||
this.ctx.logger.info('[ExpressService.asyncTask] 调用 createWaybillCode 后', {
|
||||
traceId,
|
||||
batchCount: Array.isArray(batch) ? batch.length : 0,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('异步任务执行失败:', error.message);
|
||||
this.ctx.logger.error('[ExpressService.asyncTask] 异步任务执行异常', {
|
||||
traceId,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
stack: error && error.stack ? error.stack : '',
|
||||
});
|
||||
const err_orders = batch.map(order => ({
|
||||
order_id: order.id,
|
||||
order_id: order && (order.id || order.order_id),
|
||||
business_key: order.business_key,
|
||||
}));
|
||||
const failedOrderIds = err_orders
|
||||
.map(order => Number(order && order.order_id))
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0);
|
||||
const logWarehouseId = this.getOrderLogWarehouseId(options && options.warehouse_id);
|
||||
const errorMessage = error && error.message ? String(error.message) : String(error);
|
||||
this.service.systems.orderPendingException.markPendingException(
|
||||
{
|
||||
ids: err_orders.map(order => order.order_id),
|
||||
exception_text: `订单快递分配失败: ${error.message}`,
|
||||
exception_text: `订单快递分配失败: ${errorMessage}`,
|
||||
}
|
||||
);
|
||||
await this.createAllocateExpressFailureLogs(failedOrderIds, errorMessage, logWarehouseId);
|
||||
await this.hardDeleteWaybillAsyncOrderExpressRows(err_orders, {
|
||||
platform_code: options.sys_platform_code,
|
||||
error_message: error.message,
|
||||
error_message: errorMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1592,8 +1788,18 @@ class ExpressService extends Service {
|
||||
* @return {Promise<Object>} 创建结果。
|
||||
*/
|
||||
async createWaybillCode(orders, matchedPlatform, listByWarehousePlatformCode) {
|
||||
console.log('=======================================');
|
||||
console.log('createWaybillCode 输入订单列表', orders, 'matchedPlatform', matchedPlatform, 'listByWarehousePlatformCode', listByWarehousePlatformCode);
|
||||
const traceId = this.buildWaybillTraceId({
|
||||
trace_id: listByWarehousePlatformCode && listByWarehousePlatformCode.trace_id,
|
||||
traceId: listByWarehousePlatformCode && listByWarehousePlatformCode.traceId,
|
||||
}, 'createWaybillCode');
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCode] 入口请求', {
|
||||
traceId,
|
||||
orderCount: Array.isArray(orders) ? orders.length : 0,
|
||||
orderIds: (Array.isArray(orders) ? orders : []).slice(0, 50).map(order => Number(order && (order.id || order.order_id))).filter(orderId => Number.isFinite(orderId) && orderId > 0),
|
||||
platformCode: matchedPlatform && matchedPlatform.code,
|
||||
defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface,
|
||||
warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id,
|
||||
});
|
||||
const { app, ctx } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
|
||||
@ -1626,8 +1832,6 @@ class ExpressService extends Service {
|
||||
if (!storeWarehouseModel || typeof storeWarehouseModel.findAll !== 'function' || typeof storeWarehouseModel.update !== 'function') {
|
||||
throw new Error('签约关系模型未初始化');
|
||||
}
|
||||
console.log('1');
|
||||
|
||||
const maxAttempts = 3;
|
||||
/**
|
||||
* 执行运单创建事务,并在死锁或锁等待超时时按次数重试。
|
||||
@ -1896,20 +2100,39 @@ class ExpressService extends Service {
|
||||
}
|
||||
};
|
||||
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务前', {
|
||||
traceId,
|
||||
orderCount: normalizedOrders.length,
|
||||
});
|
||||
const createWaybillResult = await executeCreateWaybillTransactionWithRetry(1);
|
||||
|
||||
console.log('2');
|
||||
console.log('事务结果', createWaybillResult);
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCode] DB 回写事务后', {
|
||||
traceId,
|
||||
successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders)
|
||||
? createWaybillResult.orders.length
|
||||
: 0,
|
||||
});
|
||||
|
||||
try {
|
||||
if (Array.isArray(createWaybillResult.orders)
|
||||
&& createWaybillResult.orders.length > 0
|
||||
&& matchedPlatform
|
||||
&& matchedPlatform.default_express_interface) {
|
||||
try {
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用前', {
|
||||
traceId,
|
||||
platformInterface: matchedPlatform.default_express_interface,
|
||||
orderCount: createWaybillResult.orders.length,
|
||||
});
|
||||
await this.dispatchWaybillAsyncPlatform(matchedPlatform.default_express_interface, {
|
||||
matchedPlatform,
|
||||
listByWarehousePlatformCode,
|
||||
orders: createWaybillResult.orders,
|
||||
trace_id: traceId,
|
||||
});
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCode] 平台后处理调用后', {
|
||||
traceId,
|
||||
platformInterface: matchedPlatform.default_express_interface,
|
||||
});
|
||||
} catch (error) {
|
||||
throw error;
|
||||
@ -1935,6 +2158,12 @@ class ExpressService extends Service {
|
||||
restoreRelationMap.set(relationKey, currentRelation);
|
||||
}
|
||||
console.error('运单后处理失败,准备回补锁定量:', error.message, 'restoreRelationList', Array.from(restoreRelationMap.values()));
|
||||
this.ctx.logger.error('[ExpressService.createWaybillCode] 平台后处理异常,准备回补锁定量', {
|
||||
traceId,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
stack: error && error.stack ? error.stack : '',
|
||||
restoreRelationList: Array.from(restoreRelationMap.values()),
|
||||
});
|
||||
if (restoreRelationMap.size > 0) {
|
||||
const restoreRelationList = Array.from(restoreRelationMap.values());
|
||||
const restoreRows = await storeWarehouseModel.findAll({
|
||||
@ -1994,6 +2223,12 @@ class ExpressService extends Service {
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[ExpressService.createWaybillCode] 处理完成', {
|
||||
traceId,
|
||||
successOrderCount: Array.isArray(createWaybillResult && createWaybillResult.orders)
|
||||
? createWaybillResult.orders.length
|
||||
: 0,
|
||||
});
|
||||
|
||||
return createWaybillResult;
|
||||
}
|
||||
|
||||
@ -159,6 +159,71 @@ const MainService = require('../main');
|
||||
* @property {number} items_weight 商品总重量。
|
||||
*/
|
||||
class ExpressPlatformService extends MainService {
|
||||
/**
|
||||
* 获取订单日志使用的操作人信息。
|
||||
*
|
||||
* 取值优先级:employees_id/employees_name -> operator_id/operator_name -> id/real_name/name。
|
||||
*
|
||||
* @return {{ id: string|null, name: string }} 操作人信息。
|
||||
*/
|
||||
getOrderLogOperator() {
|
||||
const stateUser = this.isPlainObject(this.ctx && this.ctx.state && this.ctx.state.user)
|
||||
? this.ctx.state.user
|
||||
: null;
|
||||
const ctxUser = this.isPlainObject(this.ctx && this.ctx.user)
|
||||
? this.ctx.user
|
||||
: null;
|
||||
const operatorSource = stateUser || ctxUser || {};
|
||||
|
||||
const rawOperatorId = operatorSource.employees_id ?? operatorSource.operator_id ?? operatorSource.id;
|
||||
const rawOperatorName = operatorSource.employees_name
|
||||
?? operatorSource.operator_name
|
||||
?? operatorSource.real_name
|
||||
?? operatorSource.name;
|
||||
const operatorId = rawOperatorId === undefined || rawOperatorId === null
|
||||
? null
|
||||
: String(rawOperatorId).trim() || null;
|
||||
const operatorName = rawOperatorName === undefined || rawOperatorName === null
|
||||
? 'system'
|
||||
: String(rawOperatorName).trim() || 'system';
|
||||
|
||||
return {
|
||||
id: operatorId,
|
||||
name: operatorName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建快递平台链路追踪ID。
|
||||
*
|
||||
* 优先使用入参中的 trace_id/traceId,其次使用上下文 trace 信息,最后兜底生成。
|
||||
*
|
||||
* @param {Object} [data={}] 入参。
|
||||
* @return {string} 追踪ID。
|
||||
*/
|
||||
buildExpressPlatformTraceId(data = {}) {
|
||||
const normalizedData = data && typeof data === 'object' ? data : {};
|
||||
const ctxTraceId = this.ctx && this.ctx.traceId !== undefined
|
||||
? this.ctx.traceId
|
||||
: this.ctx && this.ctx.requestId !== undefined
|
||||
? this.ctx.requestId
|
||||
: this.ctx && this.ctx.state && this.ctx.state.traceId !== undefined
|
||||
? this.ctx.state.traceId
|
||||
: '';
|
||||
const normalizedTraceId = String(
|
||||
normalizedData.trace_id
|
||||
|| normalizedData.traceId
|
||||
|| ctxTraceId
|
||||
|| ''
|
||||
).trim();
|
||||
|
||||
if (normalizedTraceId) {
|
||||
return normalizedTraceId;
|
||||
}
|
||||
|
||||
return `express_platform_trace_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 菠萝派数据处理接口。
|
||||
*
|
||||
@ -167,13 +232,29 @@ class ExpressPlatformService extends MainService {
|
||||
*/
|
||||
async polyapi(data = {}) {
|
||||
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
|
||||
const traceId = this.buildExpressPlatformTraceId(data);
|
||||
const normalizedOrders = Array.isArray(orders) ? orders : [];
|
||||
const orderIdListForLog = normalizedOrders
|
||||
.map(item => Number(item && item.order_id) || Number(item && item.order_delivery && item.order_delivery.id) || 0)
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0);
|
||||
const waveIdListForLog = normalizedOrders
|
||||
.map(item => Number(item && item.wave_id) || Number(item && item.order_delivery && item.order_delivery.wave_id) || 0)
|
||||
.filter(waveId => Number.isFinite(waveId) && waveId > 0);
|
||||
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] 入口请求', {
|
||||
traceId,
|
||||
waveIds: Array.from(new Set(waveIdListForLog)),
|
||||
orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50),
|
||||
orderCount: normalizedOrders.length,
|
||||
requestSnapshot: {
|
||||
matchedPlatformCode: matchedPlatform && matchedPlatform.code,
|
||||
defaultExpressInterface: matchedPlatform && matchedPlatform.default_express_interface,
|
||||
platformCode: listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code,
|
||||
logisticsCode: listByWarehousePlatformCode && listByWarehousePlatformCode.logistics_code,
|
||||
warehouseId: listByWarehousePlatformCode && listByWarehousePlatformCode.warehouse_id,
|
||||
},
|
||||
});
|
||||
const ExpressList = await this.service.systems.express.loadExpressList();
|
||||
console.log('matchedPlatform', JSON.stringify(matchedPlatform));
|
||||
|
||||
console.log('接收到菠萝派快递接口入参:', JSON.stringify(listByWarehousePlatformCode));
|
||||
|
||||
console.log('接收到菠萝派平台数据处理请求,入参:', JSON.stringify(orders));
|
||||
console.log('ExpressList', JSON.stringify(ExpressList));
|
||||
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
|
||||
const allocatedWaybillMap = new Map();
|
||||
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
|
||||
@ -183,6 +264,11 @@ class ExpressPlatformService extends MainService {
|
||||
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
|
||||
|
||||
if (orderIdList.length > 0) {
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号前', {
|
||||
traceId,
|
||||
orderCount: orderIdList.length,
|
||||
orderIds: orderIdList.slice(0, 50),
|
||||
});
|
||||
const allocatedWaybillRows = await orderExpressModel.findAll({
|
||||
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
|
||||
where: {
|
||||
@ -194,6 +280,11 @@ class ExpressPlatformService extends MainService {
|
||||
raw: true,
|
||||
});
|
||||
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] 查询已分配快递号后', {
|
||||
traceId,
|
||||
hitRowCount: Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows.length : 0,
|
||||
});
|
||||
|
||||
for (const row of Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows : []) {
|
||||
const orderId = Number(row && row.order_id);
|
||||
const businessKey = Number(row && row.business_key);
|
||||
@ -211,8 +302,18 @@ class ExpressPlatformService extends MainService {
|
||||
}
|
||||
const Dictionary_bizcontent = {
|
||||
};
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用前', {
|
||||
traceId,
|
||||
api: 'Differ.JH.LogisticsPlatFeatures',
|
||||
request: Dictionary_bizcontent,
|
||||
tokenPresent: Boolean(listByWarehousePlatformCode && listByWarehousePlatformCode.token),
|
||||
});
|
||||
const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
|
||||
console.log('==================\n菠萝派平台字典接口返回结果', JSON.stringify(Dictionary_result));
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 字典接口调用后', {
|
||||
traceId,
|
||||
api: 'Differ.JH.LogisticsPlatFeatures',
|
||||
response: Dictionary_result,
|
||||
});
|
||||
|
||||
const order_bizcontent = {
|
||||
orders: orders.map(order_tmp => {
|
||||
@ -226,7 +327,7 @@ class ExpressPlatformService extends MainService {
|
||||
numpackage: order.package_count || 1,
|
||||
businesstype: 'JH_Normal',
|
||||
|
||||
businessplat: order.sys_platform_code == 'KS' ? order.sys_platform_code : 'OTHERS',
|
||||
businessplat: order.sys_platform_code === 'KS' ? order.sys_platform_code : 'OTHERS',
|
||||
paymode: listByWarehousePlatformCode.paymode ?? 1,
|
||||
ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal',
|
||||
codpaymoney: order.ar_amount ?? null,
|
||||
@ -291,10 +392,26 @@ class ExpressPlatformService extends MainService {
|
||||
shoptype: matchedPlatform.shoptype,
|
||||
};
|
||||
// 调用菠萝派平台接口进行数据处理
|
||||
console.log('==================\n业务数据', JSON.stringify(order_bizcontent), '\n=========================\n');
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用前', {
|
||||
traceId,
|
||||
api: 'Differ.JH.Logistics.PostOrder',
|
||||
waveIds: Array.from(new Set(waveIdListForLog)),
|
||||
orderIds: Array.from(new Set(orderIdListForLog)).slice(0, 50),
|
||||
request: order_bizcontent,
|
||||
});
|
||||
const result = await this.service.systems.poloApi.request('Differ.JH.Logistics.PostOrder', order_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
|
||||
console.log('==================\n菠萝派平台接口返回结果', JSON.stringify(result));
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] PolyAPI 分配快递号接口调用后', {
|
||||
traceId,
|
||||
api: 'Differ.JH.Logistics.PostOrder',
|
||||
response: result,
|
||||
});
|
||||
if (result && result.code !== '10000') {
|
||||
this.ctx.logger.error('[expressPlatform.polyapi] PolyAPI 返回业务失败', {
|
||||
traceId,
|
||||
code: result.code,
|
||||
message: result.submessage,
|
||||
response: result,
|
||||
});
|
||||
throw new Error(`菠萝派平台接口返回错误信息:${result.submessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\`` || '菠萝派平台接口调用失败');
|
||||
} else if (result && result.code === '10000') {
|
||||
const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim();
|
||||
@ -363,6 +480,36 @@ class ExpressPlatformService extends MainService {
|
||||
case 'JD':
|
||||
case 'XHS':
|
||||
case 'SPH':
|
||||
case 'PDD':
|
||||
successUpdates = (result.results || []).map(item => {
|
||||
const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_');
|
||||
const waybillCode = resolveWaybillCode(item);
|
||||
return {
|
||||
warehouse_id,
|
||||
order_id,
|
||||
business_key,
|
||||
waybill_code: waybillCode,
|
||||
orderExpressValues: {
|
||||
waybill_code: waybillCode,
|
||||
signature: item.signature,
|
||||
encryptedtoken: item.encryptedtoken,
|
||||
encryptprintinfo: item.encryptprintinfo,
|
||||
create_at: new Date(),
|
||||
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
||||
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
||||
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
||||
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
||||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||||
status: 1,
|
||||
retry_count: 0,
|
||||
},
|
||||
orderDeliveryValues: {
|
||||
post_status: 'fin',
|
||||
order_flag: '',
|
||||
},
|
||||
};
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@ -414,134 +561,173 @@ class ExpressPlatformService extends MainService {
|
||||
|
||||
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
|
||||
if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) {
|
||||
await this.ctx.model.transaction(async transaction => {
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
const businessKey = Number(item.business_key) || 0;
|
||||
if (!warehouseId || !orderId || !businessKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
|
||||
where: {
|
||||
order_id: orderId,
|
||||
business_key: businessKey,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (item.orderDeliveryValues) {
|
||||
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
|
||||
await orderModel.update(item.orderDeliveryValues, {
|
||||
where: {
|
||||
id: orderId,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (storeWarehouseModel
|
||||
&& typeof storeWarehouseModel.findAll === 'function'
|
||||
&& settlementRelationMap.size > 0) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const relationList = Array.from(settlementRelationMap.values());
|
||||
const relationRows = await storeWarehouseModel.findAll({
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
|
||||
where: {
|
||||
[Op.or]: relationList.map(item => ({
|
||||
store_id: item.store_id,
|
||||
warehouse_id: item.warehouse_id,
|
||||
})),
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const relationRowMap = new Map();
|
||||
for (const row of Array.isArray(relationRows) ? relationRows : []) {
|
||||
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
|
||||
if (relationKey !== '0:0') {
|
||||
relationRowMap.set(relationKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of relationList) {
|
||||
const relationKey = `${item.store_id}:${item.warehouse_id}`;
|
||||
const row = relationRowMap.get(relationKey);
|
||||
if (!row) {
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务开始前', {
|
||||
traceId,
|
||||
successUpdateCount: successUpdates.length,
|
||||
relationCount: settlementRelationMap.size,
|
||||
sampleOrderIds: successUpdates.slice(0, 50).map(item => Number(item && item.order_id || 0)).filter(Boolean),
|
||||
});
|
||||
try {
|
||||
await this.ctx.model.transaction(async transaction => {
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
const businessKey = Number(item.business_key) || 0;
|
||||
if (!warehouseId || !orderId || !businessKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPrintQuantity = Number(row.print_quantity || 0);
|
||||
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
|
||||
const successCount = Number(item.success_count || 0);
|
||||
if (successCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
const printDecrement = successCount;
|
||||
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
|
||||
const nextPrintQuantity = currentPrintQuantity - printDecrement;
|
||||
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
|
||||
await storeWarehouseModel.update({
|
||||
print_quantity: nextPrintQuantity,
|
||||
print_quantity_locked: nextLockedQuantity,
|
||||
}, {
|
||||
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
|
||||
where: {
|
||||
id: row.id,
|
||||
order_id: orderId,
|
||||
business_key: businessKey,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
|
||||
contract_id: Number(row.id || 0),
|
||||
store_id: Number(row.store_id || 0),
|
||||
warehouse_id: Number(row.warehouse_id || 0),
|
||||
change_type: 'order_deduct',
|
||||
business_type: 'order_express',
|
||||
business_id: null,
|
||||
change_quantity: -printDecrement,
|
||||
balance_before: Math.max(0, currentPrintQuantity),
|
||||
balance_after: Math.max(0, nextPrintQuantity),
|
||||
reason: '获取快递号成功扣减',
|
||||
operator_id: null,
|
||||
created_by: null,
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
if (item.orderDeliveryValues) {
|
||||
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
|
||||
await orderModel.update(item.orderDeliveryValues, {
|
||||
where: {
|
||||
id: orderId,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (storeWarehouseModel
|
||||
&& typeof storeWarehouseModel.findAll === 'function'
|
||||
&& settlementRelationMap.size > 0) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const relationList = Array.from(settlementRelationMap.values());
|
||||
const relationRows = await storeWarehouseModel.findAll({
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
|
||||
where: {
|
||||
[Op.or]: relationList.map(item => ({
|
||||
store_id: item.store_id,
|
||||
warehouse_id: item.warehouse_id,
|
||||
})),
|
||||
},
|
||||
raw: true,
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
const relationRowMap = new Map();
|
||||
for (const row of Array.isArray(relationRows) ? relationRows : []) {
|
||||
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
|
||||
if (relationKey !== '0:0') {
|
||||
relationRowMap.set(relationKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of relationList) {
|
||||
const relationKey = `${item.store_id}:${item.warehouse_id}`;
|
||||
const row = relationRowMap.get(relationKey);
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPrintQuantity = Number(row.print_quantity || 0);
|
||||
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
|
||||
const successCount = Number(item.success_count || 0);
|
||||
if (successCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
const printDecrement = successCount;
|
||||
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
|
||||
const nextPrintQuantity = currentPrintQuantity - printDecrement;
|
||||
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
|
||||
await storeWarehouseModel.update({
|
||||
print_quantity: nextPrintQuantity,
|
||||
print_quantity_locked: nextLockedQuantity,
|
||||
}, {
|
||||
where: {
|
||||
id: row.id,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
|
||||
contract_id: Number(row.id || 0),
|
||||
store_id: Number(row.store_id || 0),
|
||||
warehouse_id: Number(row.warehouse_id || 0),
|
||||
change_type: 'order_deduct',
|
||||
business_type: 'order_express',
|
||||
business_id: null,
|
||||
change_quantity: -printDecrement,
|
||||
balance_before: Math.max(0, currentPrintQuantity),
|
||||
balance_after: Math.max(0, nextPrintQuantity),
|
||||
reason: '获取快递号成功扣减',
|
||||
operator_id: null,
|
||||
created_by: null,
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[expressPlatform.polyapi] DB 回写事务异常', {
|
||||
traceId,
|
||||
successUpdateCount: successUpdates.length,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
stack: error && error.stack ? error.stack : '',
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] DB 回写事务完成后', {
|
||||
traceId,
|
||||
successUpdateCount: successUpdates.length,
|
||||
relationCount: settlementRelationMap.size,
|
||||
});
|
||||
|
||||
const operationLogService = this.service
|
||||
&& this.service.systems
|
||||
&& this.service.systems.operationLog;
|
||||
const operator = this.getOrderLogOperator();
|
||||
const logPayloads = [];
|
||||
for (const item of successUpdates) {
|
||||
const warehouseId = Number(item.warehouse_id) || 0;
|
||||
const orderId = Number(item.order_id) || 0;
|
||||
if (!warehouseId || !orderId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.service.systems.operationLog.createOperationLog({
|
||||
logPayloads.push({
|
||||
businessType: 'order',
|
||||
businessId: `${orderId}`,
|
||||
operationCode: 'WAYBILL',
|
||||
operatorId: this.ctx.user ? this.ctx.user.id : 'system',
|
||||
operatorName: this.ctx.user ? this.ctx.user.employees_name : '系统',
|
||||
externalLogType: 'API',
|
||||
operator: {
|
||||
id: this.ctx.user ? this.ctx.user.employees_id : '0',
|
||||
name: this.ctx.user ? this.ctx.user.employees_name : '系统',
|
||||
},
|
||||
operator,
|
||||
extras: {
|
||||
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
|
||||
warehouseId,
|
||||
externalLogType: 'API',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
await operationLogService.createOperationLogs(logPayloads);
|
||||
} else {
|
||||
this.ctx.logger.warn('[expressPlatform.polyapi] operationLog 批量写入服务不可用,跳过日志写入', {
|
||||
traceId,
|
||||
count: logPayloads.length,
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] 订单操作日志写入完成', {
|
||||
traceId,
|
||||
operationLogCount: successUpdates.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
this.ctx.logger.info('[expressPlatform.polyapi] 处理完成', {
|
||||
traceId,
|
||||
orderCount: normalizedOrders.length,
|
||||
});
|
||||
return {
|
||||
flag: true,
|
||||
code: 0,
|
||||
@ -559,7 +745,6 @@ class ExpressPlatformService extends MainService {
|
||||
*/
|
||||
async cainiao(data = {}) {
|
||||
void data;
|
||||
console.log('接收到菜鸟平台数据处理请求,入参:', JSON.stringify(data));
|
||||
throw new Error('菜鸟平台接口未实现');
|
||||
}
|
||||
|
||||
@ -571,8 +756,6 @@ class ExpressPlatformService extends MainService {
|
||||
*/
|
||||
async pdd(data = {}) {
|
||||
void data;
|
||||
console.log('接收到拼多多平台数据处理请求,入参:', JSON.stringify(data));
|
||||
|
||||
throw new Error('拼多多平台接口未实现');
|
||||
}
|
||||
}
|
||||
|
||||
@ -579,6 +579,7 @@ class NoticeService extends Service {
|
||||
*/
|
||||
async resolveSubjectConfig(options = {}, subject = {}) {
|
||||
const storeModel = this.ctx.model && this.ctx.model.Store;
|
||||
const deliveryOrderService = this.ctx.service.systems && this.ctx.service.systems.deliveryOrder;
|
||||
const normalizeSubjectConfig = value => {
|
||||
if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') {
|
||||
return storeModel.normalizeSubjectConfig(value);
|
||||
@ -601,15 +602,21 @@ class NoticeService extends Service {
|
||||
const subjectId = Number(
|
||||
options.subjectId || options.subject_id || subject.id || options.warehouseId || options.warehouse_id || options.storeId || options.store_id || 0
|
||||
);
|
||||
if (!Number.isFinite(subjectId) || subjectId <= 0 || !storeModel || typeof storeModel.findByPk !== 'function') {
|
||||
if (!Number.isFinite(subjectId) || subjectId <= 0) {
|
||||
return normalizeSubjectConfig(null);
|
||||
}
|
||||
|
||||
try {
|
||||
const store = await storeModel.findByPk(subjectId, {
|
||||
attributes: [ 'subject_config' ],
|
||||
});
|
||||
return normalizeSubjectConfig(store && store.subject_config);
|
||||
if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') {
|
||||
return normalizeSubjectConfig(null);
|
||||
}
|
||||
|
||||
const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(subjectId);
|
||||
const nestedSubjectConfig = this.toObject(subjectConfig && subjectConfig.subject_config, null);
|
||||
const resolvedSubjectConfig = nestedSubjectConfig && Object.keys(nestedSubjectConfig).length > 0
|
||||
? nestedSubjectConfig
|
||||
: subjectConfig;
|
||||
return normalizeSubjectConfig(resolvedSubjectConfig);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[NoticeService.resolveSubjectConfig] load subject_config failed: %s', error.message);
|
||||
return normalizeSubjectConfig(null);
|
||||
|
||||
@ -15,6 +15,91 @@ const OPERATION_LOG_ATTRIBUTES = [
|
||||
];
|
||||
|
||||
class operationLogService extends Service {
|
||||
/**
|
||||
* 将单条日志参数转换为数据库字段。
|
||||
* @param {Object} params 日志参数。
|
||||
* @param {string} params.businessType 业务类型。
|
||||
* @param {string|number} params.businessId 业务ID。
|
||||
* @param {string} params.operationCode 操作编码。
|
||||
* @param {Object} [params.operator={}] 操作人信息。
|
||||
* @param {Object} [params.extras={}] 扩展字段。
|
||||
* @param {Object|null} [params.beforeChanges=null] 操作前快照。
|
||||
* @return {Object} 可直接落库的日志数据。
|
||||
*/
|
||||
buildOperationLogData(params = {}) {
|
||||
const { ctx } = this;
|
||||
const {
|
||||
businessType,
|
||||
businessId,
|
||||
operationCode,
|
||||
operator = {},
|
||||
beforeChanges = null,
|
||||
extras = {},
|
||||
} = params;
|
||||
|
||||
return {
|
||||
business_type: businessType,
|
||||
business_id: String(businessId),
|
||||
operation_code: operationCode,
|
||||
operator_id: operator?.id || null,
|
||||
operator_name: operator?.name || null,
|
||||
external_log_type: extras.externalLogType || 'NONE',
|
||||
external_log_id: extras.externalLogId || null,
|
||||
warehouse_id: extras.warehouseId || null,
|
||||
before_changes: beforeChanges,
|
||||
platform_code: ctx.user?.platform_code || 'SYSTEM',
|
||||
message: extras.message || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范并校验日志查询入参,强制要求业务ID与仓库ID。
|
||||
* @param {Object} query 查询参数。
|
||||
* @param {string} businessType 业务类型。
|
||||
* @return {{ where: Object, id: string|number, warehouseId: string|number }} 查询条件。
|
||||
*/
|
||||
buildBusinessLogWhere(query = {}, businessType) {
|
||||
const requestQuery = query && typeof query === 'object' ? query : {};
|
||||
const {
|
||||
id,
|
||||
warehouseId,
|
||||
} = requestQuery;
|
||||
|
||||
if (!id) {
|
||||
throw new Error('id不能为空');
|
||||
}
|
||||
|
||||
if (!warehouseId) {
|
||||
throw new Error('仓库id不能为空');
|
||||
}
|
||||
|
||||
return {
|
||||
where: {
|
||||
business_type: businessType,
|
||||
business_id: id,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
id,
|
||||
warehouseId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将日志模型结果格式化为接口输出结构。
|
||||
* @param {Object[]} rows 日志行数据。
|
||||
* @return {Object[]} 格式化后的日志列表。
|
||||
*/
|
||||
formatOperationLogRows(rows = []) {
|
||||
const { app } = this;
|
||||
return rows.map(item => {
|
||||
const itemTmp = JSON.parse(JSON.stringify(item));
|
||||
itemTmp.operation_name = app.getOperationCodeName(item.operation_code);
|
||||
itemTmp.platform_name = app.getPlatformName(item.platform_code);
|
||||
itemTmp.created_at = app.formatDate(itemTmp.created_at);
|
||||
return itemTmp;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用操作日志记录方法
|
||||
* @param {Object} params 日志参数
|
||||
@ -32,34 +117,25 @@ class operationLogService extends Service {
|
||||
* @param {number} params.extras.externalLogId 外部日志ID
|
||||
* @param {number} params.extras.warehouseId 仓库ID
|
||||
* @param {string} params.extras.message 日志信息
|
||||
* @param {Object} [params.transaction] 事务对象(可选)
|
||||
*
|
||||
*/
|
||||
async createOperationLog(params) {
|
||||
async createOperationLog(params = {}) {
|
||||
const { ctx } = this;
|
||||
const {
|
||||
businessType,
|
||||
businessId,
|
||||
operationCode,
|
||||
operator = {},
|
||||
beforeChanges = null,
|
||||
extras = {},
|
||||
transaction,
|
||||
} = params;
|
||||
try {
|
||||
const logData = {
|
||||
business_type: businessType,
|
||||
business_id: String(businessId),
|
||||
operation_code: operationCode,
|
||||
operator_id: operator?.id || null,
|
||||
operator_name: operator?.name || null,
|
||||
external_log_type: extras.externalLogType || 'NONE',
|
||||
external_log_id: extras.externalLogId || null,
|
||||
warehouse_id: extras.warehouseId || null,
|
||||
before_changes: beforeChanges,
|
||||
platform_code: ctx.user?.platform_code || 'SYSTEM',
|
||||
message: extras.message || null,
|
||||
};
|
||||
const logData = this.buildOperationLogData(params);
|
||||
|
||||
const result = await ctx.model.OperationLog.create(logData);
|
||||
const createOptions = {};
|
||||
if (transaction) {
|
||||
createOptions.transaction = transaction;
|
||||
}
|
||||
|
||||
const result = await ctx.model.OperationLog.create(logData, createOptions);
|
||||
ctx.logger.info(`[OperationLog] 记录操作日志成功,ID: ${result.id}, Business: ${businessType}/${businessId}`);
|
||||
return result;
|
||||
} catch (error) {
|
||||
@ -69,6 +145,48 @@ class operationLogService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量写入操作日志,优先使用 bulkCreate,失败时自动降级单条写入。
|
||||
* @param {Array<Object>} paramsList 日志参数数组。
|
||||
* @param {Object} [options={}] 写入选项。
|
||||
* @param {Object} [options.transaction] 事务对象(可选)。
|
||||
* @return {Promise<Array<Object|null>>} 写入结果数组。
|
||||
*/
|
||||
async createOperationLogs(paramsList = [], options = {}) {
|
||||
const { ctx } = this;
|
||||
const requestOptions = options && typeof options === 'object' ? options : {};
|
||||
const transaction = requestOptions.transaction;
|
||||
const normalizedParamsList = Array.isArray(paramsList) ? paramsList.filter(Boolean) : [];
|
||||
|
||||
if (normalizedParamsList.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const operationLogModel = ctx.model && ctx.model.OperationLog;
|
||||
if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') {
|
||||
ctx.logger.warn('[OperationLog] OperationLog.bulkCreate 不可用,降级单条写入');
|
||||
return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({
|
||||
...item,
|
||||
transaction: item && item.transaction ? item.transaction : transaction,
|
||||
})));
|
||||
}
|
||||
|
||||
try {
|
||||
const rows = normalizedParamsList.map(item => this.buildOperationLogData(item));
|
||||
const bulkCreateOptions = {};
|
||||
if (transaction) {
|
||||
bulkCreateOptions.transaction = transaction;
|
||||
}
|
||||
return await operationLogModel.bulkCreate(rows, bulkCreateOptions);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[OperationLog] 批量记录操作日志失败,降级单条写入: ${error.message}`, error);
|
||||
return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({
|
||||
...item,
|
||||
transaction: item && item.transaction ? item.transaction : transaction,
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按业务类型查询操作日志分页数据。
|
||||
* @param {Object} query 查询参数。
|
||||
@ -80,28 +198,13 @@ class operationLogService extends Service {
|
||||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||||
*/
|
||||
async queryLogsByBusinessType(query = {}, businessType) {
|
||||
const { ctx, app } = this;
|
||||
const { ctx } = this;
|
||||
const requestQuery = query && typeof query === 'object' ? query : {};
|
||||
const {
|
||||
id,
|
||||
warehouseId,
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
} = requestQuery;
|
||||
|
||||
const where = {
|
||||
business_type: businessType,
|
||||
};
|
||||
|
||||
if (!id) {
|
||||
throw new Error('id不能为空');
|
||||
}
|
||||
where.business_id = id;
|
||||
|
||||
if (!warehouseId) {
|
||||
throw new Error('仓库id不能为空');
|
||||
}
|
||||
where.warehouse_id = warehouseId;
|
||||
const { where } = this.buildBusinessLogWhere(requestQuery, businessType);
|
||||
|
||||
const currentPage = Number.parseInt(page, 10) || 1;
|
||||
const currentPageSize = Number.parseInt(pageSize, 10) || 20;
|
||||
@ -118,13 +221,7 @@ class operationLogService extends Service {
|
||||
const rows = Array.isArray(result.rows) ? result.rows : [];
|
||||
|
||||
return {
|
||||
list: rows.map(item => {
|
||||
const itemTmp = JSON.parse(JSON.stringify(item));
|
||||
itemTmp.operation_name = app.getOperationCodeName(item.operation_code);
|
||||
itemTmp.platform_name = app.getPlatformName(item.platform_code);
|
||||
itemTmp.created_at = app.formatDate(itemTmp.created_at);
|
||||
return itemTmp;
|
||||
}),
|
||||
list: this.formatOperationLogRows(rows),
|
||||
pagination: {
|
||||
page: currentPage,
|
||||
pageSize: currentPageSize,
|
||||
@ -160,6 +257,41 @@ class operationLogService extends Service {
|
||||
return await this.queryLogsByBusinessType(query, 'order');
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单操作日志(不分页,返回全部)。
|
||||
* @param {Object} query 查询参数。
|
||||
* @param {string|number} query.id 订单ID。
|
||||
* @param {string|number} query.warehouseId 仓库ID。
|
||||
* @return {Promise<Object[]>} 日志列表。
|
||||
*/
|
||||
async queryAllOrderLogs(query = {}) {
|
||||
return await this.queryAllLogsByBusinessType(query, 'order');
|
||||
}
|
||||
|
||||
/**
|
||||
* 按业务类型查询日志全量数据(不分页)。
|
||||
* @param {Object} query 查询参数。
|
||||
* @param {string|number} query.id 业务ID。
|
||||
* @param {string|number} query.warehouseId 仓库ID。
|
||||
* @param {string} businessType 业务类型。
|
||||
* @return {Promise<Object[]>} 日志列表。
|
||||
*/
|
||||
async queryAllLogsByBusinessType(query = {}, businessType) {
|
||||
const { ctx } = this;
|
||||
const requestQuery = query && typeof query === 'object' ? query : {};
|
||||
const { where } = this.buildBusinessLogWhere(requestQuery, businessType);
|
||||
|
||||
const rows = await ctx.model.OperationLog.findAll({
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
attributes: OPERATION_LOG_ATTRIBUTES,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const normalizedRows = Array.isArray(rows) ? rows : [];
|
||||
return this.formatOperationLogRows(normalizedRows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询收货单操作日志。
|
||||
* @param {Object} query 查询参数。
|
||||
|
||||
369
app/service/systems/order_print.js
Normal file
369
app/service/systems/order_print.js
Normal file
@ -0,0 +1,369 @@
|
||||
'use strict';
|
||||
|
||||
const { Op } = require('sequelize');
|
||||
const OrderBaseService = require('../systemMethods/order/base');
|
||||
|
||||
class OrderPrintSystemService extends OrderBaseService {
|
||||
/**
|
||||
* 获取波次打印数据。
|
||||
*
|
||||
* @param {Object} params 请求参数。
|
||||
* @param {Array<number|string>} params.waveIds 波次ID数组。
|
||||
* @param {number|string} params.warehouseId 仓库ID。
|
||||
* @return {Promise<Object>} 通用打印数据结构。
|
||||
*/
|
||||
async getWavePrintData(params = {}) {
|
||||
const requestParams = this.isPlainObject(params) ? params : {};
|
||||
const {
|
||||
waveIds,
|
||||
warehouseId,
|
||||
} = requestParams;
|
||||
|
||||
const normalizedWaveIds = this.normalizeWaveIds(waveIds);
|
||||
if (normalizedWaveIds.length === 0) {
|
||||
throw new Error('wave_ids 必填,且必须为非空数组');
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = this.resolveWarehouseId(warehouseId);
|
||||
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, normalizedWaveIds);
|
||||
if (waveRows.length === 0) {
|
||||
return this.buildEmptyResult(normalizedWaveIds);
|
||||
}
|
||||
|
||||
const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id)));
|
||||
const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId));
|
||||
const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId));
|
||||
const orderRows = await this.queryOrdersByWaveIds(hitWaveIds, normalizedWarehouseId);
|
||||
const {
|
||||
validWaveIds,
|
||||
filteredWaveIds,
|
||||
} = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows);
|
||||
|
||||
return this.buildWavePrintResult({
|
||||
waveRows,
|
||||
orderRows,
|
||||
hitWaveIds: validWaveIds,
|
||||
missingWaveIds,
|
||||
filteredWaveIds,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化波次ID数组(去重与数字化)。
|
||||
*
|
||||
* @param {Array<number|string>} waveIds 原始波次ID数组。
|
||||
* @return {Array<number>} 规范化后的波次ID数组。
|
||||
*/
|
||||
normalizeWaveIds(waveIds = []) {
|
||||
if (!Array.isArray(waveIds)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const normalizedSet = new Set();
|
||||
|
||||
for (const rawId of waveIds) {
|
||||
const normalizedId = Number(String(rawId ?? '').trim());
|
||||
if (Number.isInteger(normalizedId) && normalizedId > 0) {
|
||||
normalizedSet.add(normalizedId);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(normalizedSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并校验仓库ID。
|
||||
*
|
||||
* @param {number|string} warehouseId 入参仓库ID。
|
||||
* @return {number} 规范化后的仓库ID。
|
||||
*/
|
||||
resolveWarehouseId(warehouseId) {
|
||||
const contextWarehouseId = Number(this.getWarehouseId() || 0);
|
||||
if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) {
|
||||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = Number(String(warehouseId ?? '').trim());
|
||||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw new Error('warehouse_id 必填且必须为正整数');
|
||||
}
|
||||
|
||||
if (normalizedWarehouseId !== contextWarehouseId) {
|
||||
throw new Error('warehouse_id 必须与当前用户上下文 store_id 保持一致');
|
||||
}
|
||||
|
||||
return normalizedWarehouseId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按波次ID批量查询波次信息。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Array<number>} waveIds 波次ID数组。
|
||||
* @return {Promise<Array<Object>>} 波次基础信息。
|
||||
*/
|
||||
async queryWavesByIds(warehouseId, waveIds = []) {
|
||||
if (!Array.isArray(waveIds) || waveIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const querySql = `
|
||||
SELECT wave_id, wave_no
|
||||
FROM wms_wave_batch
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND wave_id IN (:waveIds)
|
||||
AND wave_status <> -1
|
||||
`;
|
||||
|
||||
const rows = await this.ctx.model.query(querySql, {
|
||||
replacements: {
|
||||
warehouseId,
|
||||
waveIds,
|
||||
},
|
||||
type: this.ctx.model.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 按波次ID批量查询订单明细。
|
||||
*
|
||||
* @param {Array<number>} waveIds 波次ID数组。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Array<Object>>} 订单明细列表。
|
||||
*/
|
||||
async queryOrdersByWaveIds(waveIds = [], warehouseId) {
|
||||
if (!Array.isArray(waveIds) || waveIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const orderModel = await this.getOrderModel('order', warehouseId);
|
||||
const rows = await orderModel.findAll({
|
||||
attributes: [
|
||||
'id',
|
||||
'delivery_order_code',
|
||||
'source_order_codes',
|
||||
'wave_id',
|
||||
'wave_no',
|
||||
'name',
|
||||
'tel',
|
||||
'mobile',
|
||||
'province',
|
||||
'city',
|
||||
'area',
|
||||
'town',
|
||||
'detail_address',
|
||||
'sys_platform_code',
|
||||
'sys_platform_name',
|
||||
'logistics_name',
|
||||
'post_status',
|
||||
'status',
|
||||
'outbound_status',
|
||||
'print_status',
|
||||
'items_count',
|
||||
'items_total',
|
||||
'items_weight',
|
||||
'create_at',
|
||||
'pay_time',
|
||||
],
|
||||
where: {
|
||||
wave_id: {
|
||||
[Op.in]: waveIds,
|
||||
},
|
||||
},
|
||||
order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤快递未完全分配的波次。
|
||||
*
|
||||
* 规则:仅当波次下全部订单的 post_status 都为 fin 时,才视为快递已完全分配。
|
||||
*
|
||||
* @param {Array<number>} hitWaveIds 命中的波次ID数组。
|
||||
* @param {Array<Object>} orderRows 波次订单列表。
|
||||
* @return {{ validWaveIds: Array<number>, filteredWaveIds: Array<Object> }} 过滤结果。
|
||||
*/
|
||||
filterFullyAssignedExpressWaves(hitWaveIds = [], orderRows = []) {
|
||||
const statsMap = new Map();
|
||||
for (const waveId of hitWaveIds) {
|
||||
statsMap.set(Number(waveId), {
|
||||
total: 0,
|
||||
fin: 0,
|
||||
});
|
||||
}
|
||||
|
||||
for (const row of orderRows) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
const stats = statsMap.get(waveId);
|
||||
if (!stats) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const postStatus = String(row && row.post_status || '').trim();
|
||||
stats.total += 1;
|
||||
if (postStatus === 'fin') {
|
||||
stats.fin += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const validWaveIds = [];
|
||||
const filteredWaveIds = [];
|
||||
for (const waveId of hitWaveIds) {
|
||||
const stats = statsMap.get(waveId) || { total: 0, fin: 0 };
|
||||
const isFullyAssigned = stats.total > 0 && stats.fin === stats.total;
|
||||
if (isFullyAssigned) {
|
||||
validWaveIds.push(waveId);
|
||||
} else {
|
||||
filteredWaveIds.push({
|
||||
wave_id: waveId,
|
||||
reason: '快递未完全分配',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
validWaveIds,
|
||||
filteredWaveIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成空结果结构。
|
||||
*
|
||||
* @param {Array<number>} normalizedWaveIds 规范化后的波次ID数组。
|
||||
* @return {Object} 空结果。
|
||||
*/
|
||||
buildEmptyResult(normalizedWaveIds = []) {
|
||||
return {
|
||||
summary: {
|
||||
total_waves: 0,
|
||||
total_orders: 0,
|
||||
},
|
||||
wave_list: [],
|
||||
ext: {
|
||||
missing_wave_ids: normalizedWaveIds,
|
||||
filtered_wave_ids: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装通用波次打印返回结构。
|
||||
*
|
||||
* @param {Object} payload 聚合输入。
|
||||
* @param {Array<Object>} payload.waveRows 波次列表。
|
||||
* @param {Array<Object>} payload.orderRows 订单列表。
|
||||
* @param {Array<number>} payload.hitWaveIds 命中的波次ID数组。
|
||||
* @param {Array<number>} payload.missingWaveIds 未命中的波次ID数组。
|
||||
* @param {Array<Object>} payload.filteredWaveIds 被过滤的波次及原因。
|
||||
* @return {Object} 波次打印返回结果。
|
||||
*/
|
||||
buildWavePrintResult(payload = {}) {
|
||||
const {
|
||||
waveRows = [],
|
||||
orderRows = [],
|
||||
hitWaveIds = [],
|
||||
missingWaveIds = [],
|
||||
filteredWaveIds = [],
|
||||
} = this.isPlainObject(payload) ? payload : {};
|
||||
|
||||
const waveMetaMap = new Map();
|
||||
for (const row of waveRows) {
|
||||
const waveId = Number(row && row.wave_id || 0);
|
||||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
waveMetaMap.set(waveId, {
|
||||
wave_id: waveId,
|
||||
wave_no: String(row && row.wave_no || '').trim(),
|
||||
});
|
||||
}
|
||||
|
||||
const groupedWaveMap = new Map();
|
||||
for (const waveId of hitWaveIds) {
|
||||
const waveMeta = waveMetaMap.get(waveId);
|
||||
if (!waveMeta) {
|
||||
continue;
|
||||
}
|
||||
|
||||
groupedWaveMap.set(waveId, {
|
||||
wave_id: waveMeta.wave_id,
|
||||
wave_no: waveMeta.wave_no,
|
||||
order_count: 0,
|
||||
orders: [],
|
||||
});
|
||||
}
|
||||
|
||||
for (const order of orderRows) {
|
||||
const waveId = Number(order && order.wave_id || 0);
|
||||
const groupedWave = groupedWaveMap.get(waveId);
|
||||
if (!groupedWave) {
|
||||
continue;
|
||||
}
|
||||
|
||||
groupedWave.orders.push({
|
||||
order_id: Number(order && order.id || 0),
|
||||
order_no: String(order && (order.delivery_order_code || order.source_order_codes) || '').trim(),
|
||||
wave_id: waveId,
|
||||
wave_no: String(order && order.wave_no || '').trim() || groupedWave.wave_no,
|
||||
receiver: {
|
||||
name: String(order && order.name || '').trim(),
|
||||
mobile: String(order && order.mobile || '').trim(),
|
||||
tel: String(order && order.tel || '').trim(),
|
||||
province: String(order && order.province || '').trim(),
|
||||
city: String(order && order.city || '').trim(),
|
||||
area: String(order && order.area || '').trim(),
|
||||
town: String(order && order.town || '').trim(),
|
||||
detail_address: String(order && order.detail_address || '').trim(),
|
||||
},
|
||||
channel: {
|
||||
sys_platform_code: String(order && order.sys_platform_code || '').trim(),
|
||||
sys_platform_name: String(order && order.sys_platform_name || '').trim(),
|
||||
logistics_name: String(order && order.logistics_name || '').trim(),
|
||||
},
|
||||
status: {
|
||||
order_status: String(order && order.status || '').trim(),
|
||||
outbound_status: String(order && order.outbound_status || '').trim(),
|
||||
print_status: String(order && order.print_status || '').trim(),
|
||||
},
|
||||
metrics: {
|
||||
items_count: Number(order && order.items_count || 0),
|
||||
items_total: Number(order && order.items_total || 0),
|
||||
items_weight: Number(order && order.items_weight || 0),
|
||||
},
|
||||
times: {
|
||||
create_at: order && order.create_at || null,
|
||||
pay_time: order && order.pay_time || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const waveList = Array.from(groupedWaveMap.values());
|
||||
waveList.sort((a, b) => String(a.wave_no || '').localeCompare(String(b.wave_no || '')));
|
||||
let totalOrders = 0;
|
||||
for (const wave of waveList) {
|
||||
wave.order_count = wave.orders.length;
|
||||
totalOrders += wave.order_count;
|
||||
}
|
||||
|
||||
return {
|
||||
summary: {
|
||||
total_waves: waveList.length,
|
||||
total_orders: totalOrders,
|
||||
},
|
||||
wave_list: waveList,
|
||||
ext: {
|
||||
missing_wave_ids: missingWaveIds,
|
||||
filtered_wave_ids: filteredWaveIds,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderPrintSystemService;
|
||||
@ -5,6 +5,7 @@ const MainService = require('../main');
|
||||
const STORAGE_STATUS_FIN = 'fin';
|
||||
const STORAGE_STATUS_ERROR = 'error';
|
||||
const ORDER_STEP_EXCEPTION = 3;
|
||||
const ALLOCATION_LOG_SAMPLE_LIMIT = 20;
|
||||
|
||||
/**
|
||||
* 规范化块状日志的输出值。
|
||||
@ -97,6 +98,22 @@ function writeAllocationTextLog(title, payload) {
|
||||
process.stdout.write(`${formatAllocationLogBlock(title, payload)}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成数组日志摘要,避免输出全量数据。
|
||||
*
|
||||
* @param {Array<unknown>} list 原始数组。
|
||||
* @param {number} [limit=ALLOCATION_LOG_SAMPLE_LIMIT] 采样数量上限。
|
||||
* @return {{count: number, sample: Array<unknown>}} 摘要信息。
|
||||
*/
|
||||
function summarizeArrayForLog(list, limit = ALLOCATION_LOG_SAMPLE_LIMIT) {
|
||||
const normalizedList = Array.isArray(list) ? list : [];
|
||||
|
||||
return {
|
||||
count: normalizedList.length,
|
||||
sample: normalizedList.slice(0, limit),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将输入值规范化为布尔值。
|
||||
*
|
||||
@ -196,10 +213,9 @@ function summarizeStorageRows(stockId, storageRows = []) {
|
||||
*
|
||||
* @param {Object} left 左侧库存。
|
||||
* @param {Object} right 右侧库存。
|
||||
* @param {boolean} prioritizeStorage 是否优先使用存储储位。
|
||||
* @return {number} 排序结果。
|
||||
*/
|
||||
function compareStorageRows(left, right, prioritizeStorage) {
|
||||
function compareStorageRows(left, right) {
|
||||
const leftHasProductionDate = Boolean(left.production_date);
|
||||
const rightHasProductionDate = Boolean(right.production_date);
|
||||
|
||||
@ -413,65 +429,6 @@ function normalizeOrderIds(data = {}) {
|
||||
return Array.from(new Set(orderIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化订单创建渠道。
|
||||
*
|
||||
* @param {unknown} value 创建渠道原始值。
|
||||
* @return {string} 规范化后的渠道码。
|
||||
*/
|
||||
function normalizeCreateChannel(value) {
|
||||
const normalizedValue = String(value || '').trim().toUpperCase();
|
||||
|
||||
return normalizedValue || 'MANUAL';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按创建渠道对订单分组。
|
||||
*
|
||||
* @param {Array<Object>} orders 订单列表。
|
||||
* @return {Array<Object>} 分组结果。
|
||||
*/
|
||||
function groupOrdersByCreateChannel(orders = []) {
|
||||
const groupedOrderMap = new Map();
|
||||
|
||||
for (const order of Array.isArray(orders) ? orders : []) {
|
||||
if (!order || typeof order !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const createChannel = normalizeCreateChannel(order.create_channel);
|
||||
let groupedOrder = groupedOrderMap.get(createChannel);
|
||||
|
||||
if (!groupedOrder) {
|
||||
groupedOrder = {
|
||||
create_channel: createChannel,
|
||||
order_ids: [],
|
||||
order_count: 0,
|
||||
orders: [],
|
||||
};
|
||||
groupedOrderMap.set(createChannel, groupedOrder);
|
||||
}
|
||||
|
||||
const orderId = toNumber(order.id, 0);
|
||||
if (orderId > 0) {
|
||||
groupedOrder.order_ids.push(orderId);
|
||||
}
|
||||
|
||||
groupedOrder.order_count += 1;
|
||||
groupedOrder.orders.push({
|
||||
id: orderId,
|
||||
delivery_order_code: String(order.delivery_order_code || '').trim(),
|
||||
create_channel: createChannel,
|
||||
sync_status: String(order.sync_status || '').trim() || 'padding',
|
||||
express_code: String(order.express_code || '').trim(),
|
||||
post_status: String(order.post_status || '').trim() || 'none',
|
||||
storage_status: String(order.storage_status || '').trim() || 'none',
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(groupedOrderMap.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化取消储位分配相关入参。
|
||||
*
|
||||
@ -515,6 +472,9 @@ class OrderStorageAllocationService extends MainService {
|
||||
async allocatePicking(data = {}) {
|
||||
const { ctx, app } = this;
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const progressCallback = typeof requestData.progress_callback === 'function'
|
||||
? requestData.progress_callback
|
||||
: null;
|
||||
const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
|
||||
const orderIds = normalizeOrderIds(requestData);
|
||||
const allowStorageLocation = normalizeBooleanFlag(
|
||||
@ -562,6 +522,19 @@ class OrderStorageAllocationService extends MainService {
|
||||
const transaction = await ctx.model.transaction();
|
||||
const { Op } = app.Sequelize;
|
||||
const now = new Date();
|
||||
const notifyProgress = async payload => {
|
||||
if (typeof progressCallback !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await progressCallback(payload);
|
||||
} catch (error) {
|
||||
if (ctx.logger && typeof ctx.logger.warn === 'function') {
|
||||
ctx.logger.warn('[OrderStorageAllocationService.allocatePicking] 上报进度回调失败: %s', error && error.message ? error.message : error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务已创建', {
|
||||
warehouseId,
|
||||
@ -599,7 +572,8 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单主表查询完成', {
|
||||
warehouseId,
|
||||
requestedOrderIds: orderIds,
|
||||
requestedOrderCount: orderIds.length,
|
||||
requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
orderRowCount: Array.isArray(orderRows) ? orderRows.length : 0,
|
||||
});
|
||||
|
||||
@ -655,27 +629,34 @@ class OrderStorageAllocationService extends MainService {
|
||||
pendingOrderIds.push(orderId);
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单进入待分配列表', {
|
||||
orderId,
|
||||
pendingOrderIds,
|
||||
pendingOrderCount: pendingOrderIds.length,
|
||||
pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
});
|
||||
}
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单过滤完成', {
|
||||
requestedOrderIds: orderIds,
|
||||
pendingOrderIds,
|
||||
skippedOrders,
|
||||
requestedOrderCount: orderIds.length,
|
||||
pendingOrderCount: pendingOrderIds.length,
|
||||
skippedOrderCount: skippedOrders.length,
|
||||
pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
});
|
||||
|
||||
if (pendingOrderIds.length === 0) {
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 无需分配的订单,准备提交事务', {
|
||||
warehouseId,
|
||||
skippedOrders,
|
||||
skippedOrderCount: skippedOrders.length,
|
||||
skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
});
|
||||
await transaction.commit();
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', {
|
||||
warehouseId,
|
||||
requestedOrderIds: orderIds,
|
||||
pendingOrderIds,
|
||||
skippedOrders,
|
||||
requestedOrderCount: orderIds.length,
|
||||
pendingOrderCount: pendingOrderIds.length,
|
||||
skippedOrderCount: skippedOrders.length,
|
||||
requestedOrderSampleIds: orderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
});
|
||||
return {
|
||||
code: 200,
|
||||
@ -705,7 +686,8 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细查询完成', {
|
||||
warehouseId,
|
||||
pendingOrderIds,
|
||||
pendingOrderCount: pendingOrderIds.length,
|
||||
pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
orderItemRowCount: Array.isArray(orderItemRows) ? orderItemRows.length : 0,
|
||||
});
|
||||
|
||||
@ -733,8 +715,10 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细归集完成', {
|
||||
warehouseId,
|
||||
pendingOrderIds,
|
||||
stockIds,
|
||||
pendingOrderCount: pendingOrderIds.length,
|
||||
pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
stockIdCount: stockIds.length,
|
||||
stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
});
|
||||
|
||||
if (stockIds.length > 0) {
|
||||
@ -755,7 +739,8 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录预锁定完成', {
|
||||
warehouseId,
|
||||
stockIds,
|
||||
stockIdCount: stockIds.length,
|
||||
stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
});
|
||||
|
||||
const storageRows = stockIds.length > 0
|
||||
@ -799,7 +784,8 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 可分配库存查询完成', {
|
||||
warehouseId,
|
||||
stockIds,
|
||||
stockIdCount: stockIds.length,
|
||||
stockIdSample: stockIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
storageRowCount: Array.isArray(storageRows) ? storageRows.length : 0,
|
||||
});
|
||||
|
||||
@ -840,6 +826,14 @@ class OrderStorageAllocationService extends MainService {
|
||||
const stockAllocationMap = new Map();
|
||||
const storageAllocationMap = new Map();
|
||||
const orderResults = [];
|
||||
const totalCount = pendingOrderIds.length;
|
||||
let processedCount = 0;
|
||||
|
||||
await notifyProgress({
|
||||
status: 'running',
|
||||
total_count: totalCount,
|
||||
processed_count: processedCount,
|
||||
});
|
||||
|
||||
for (const orderId of pendingOrderIds) {
|
||||
const orderRow = orderMap.get(orderId);
|
||||
@ -918,7 +912,7 @@ class OrderStorageAllocationService extends MainService {
|
||||
const storageRowsForStock = storageRowsByStockId.get(stockId) || [];
|
||||
const candidateStorageRows = storageRowsForStock
|
||||
.slice()
|
||||
.sort((left, right) => compareStorageRows(left, right, allowStorageSpace));
|
||||
.sort((left, right) => compareStorageRows(left, right));
|
||||
|
||||
let shortageReason = '';
|
||||
let shortageDiagnostics = null;
|
||||
@ -1122,45 +1116,114 @@ class OrderStorageAllocationService extends MainService {
|
||||
orderId,
|
||||
orderResult: orderResults[orderResults.length - 1],
|
||||
});
|
||||
|
||||
processedCount += 1;
|
||||
await notifyProgress({
|
||||
status: 'running',
|
||||
total_count: totalCount,
|
||||
processed_count: processedCount,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [ stockId, quantity ] of stockAllocationMap.entries()) {
|
||||
if (quantity <= 0) {
|
||||
continue;
|
||||
}
|
||||
const stockLockEntries = Array.from(stockAllocationMap.entries())
|
||||
.map(([ stockId, quantity ]) => ({
|
||||
stockId: toNumber(stockId, 0),
|
||||
quantity: toNumber(quantity, 0),
|
||||
}))
|
||||
.filter(item => item.stockId > 0 && item.quantity > 0);
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备更新库存主表锁定数量', {
|
||||
if (stockLockEntries.length > 0) {
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备批量更新库存主表锁定数量', {
|
||||
warehouseId,
|
||||
stockId,
|
||||
quantity,
|
||||
stockLockEntries,
|
||||
});
|
||||
|
||||
const stockRecord = await ctx.model.StockWarehouse.findByPk(stockId, {
|
||||
const lockStockIds = stockLockEntries.map(item => item.stockId);
|
||||
const existingStockRows = await ctx.model.StockWarehouse.findAll({
|
||||
attributes: [ 'id' ],
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: lockStockIds,
|
||||
},
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!stockRecord) {
|
||||
const existingStockIdSet = new Set(
|
||||
(Array.isArray(existingStockRows) ? existingStockRows : [])
|
||||
.map(row => toNumber(row && row.id, 0))
|
||||
.filter(stockId => stockId > 0)
|
||||
);
|
||||
|
||||
const missingStockEntry = stockLockEntries.find(item => !existingStockIdSet.has(item.stockId));
|
||||
if (missingStockEntry) {
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主记录缺失,准备抛错', {
|
||||
warehouseId,
|
||||
stockId,
|
||||
quantity,
|
||||
stockId: missingStockEntry.stockId,
|
||||
quantity: missingStockEntry.quantity,
|
||||
});
|
||||
throw new Error(`库存主记录不存在: ${stockId}`);
|
||||
throw new Error(`库存主记录不存在: ${missingStockEntry.stockId}`);
|
||||
}
|
||||
|
||||
await stockRecord.increment('locked_quantity', {
|
||||
by: quantity,
|
||||
transaction,
|
||||
silent: true,
|
||||
});
|
||||
await stockRecord.reload({ transaction });
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主表锁定数量更新完成', {
|
||||
const updateSqlReplacements = {
|
||||
warehouseId,
|
||||
stockId,
|
||||
quantity,
|
||||
locked_quantity: stockRecord.locked_quantity,
|
||||
stockIds: lockStockIds,
|
||||
};
|
||||
const caseSqlSegments = [];
|
||||
|
||||
stockLockEntries.forEach((item, index) => {
|
||||
const stockIdKey = `stockId_${index}`;
|
||||
const quantityKey = `quantity_${index}`;
|
||||
updateSqlReplacements[stockIdKey] = item.stockId;
|
||||
updateSqlReplacements[quantityKey] = item.quantity;
|
||||
caseSqlSegments.push(`WHEN :${stockIdKey} THEN :${quantityKey}`);
|
||||
});
|
||||
|
||||
const updateStockLockSql = `
|
||||
UPDATE wms_stock_warehouse
|
||||
SET locked_quantity = locked_quantity + CASE id
|
||||
${caseSqlSegments.join('\n ')}
|
||||
ELSE 0
|
||||
END
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND id IN (:stockIds)
|
||||
`;
|
||||
|
||||
await ctx.model.query(updateStockLockSql, {
|
||||
replacements: updateSqlReplacements,
|
||||
transaction,
|
||||
});
|
||||
|
||||
const updatedStockRows = await ctx.model.StockWarehouse.findAll({
|
||||
attributes: [ 'id', 'locked_quantity' ],
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: lockStockIds,
|
||||
},
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const updatedLockedQuantityMap = new Map(
|
||||
(Array.isArray(updatedStockRows) ? updatedStockRows : []).map(row => [
|
||||
toNumber(row && row.id, 0),
|
||||
toNumber(row && row.locked_quantity, 0),
|
||||
])
|
||||
);
|
||||
|
||||
for (const item of stockLockEntries) {
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存主表锁定数量更新完成', {
|
||||
warehouseId,
|
||||
stockId: item.stockId,
|
||||
quantity: item.quantity,
|
||||
locked_quantity: toNumber(updatedLockedQuantityMap.get(item.stockId), 0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (pickingRows.length > 0) {
|
||||
@ -1175,26 +1238,30 @@ class OrderStorageAllocationService extends MainService {
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备提交事务', {
|
||||
warehouseId,
|
||||
pendingOrderIds,
|
||||
skippedOrders,
|
||||
orderResults,
|
||||
stockLockSummary: Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({
|
||||
pendingOrderCount: pendingOrderIds.length,
|
||||
pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
skippedOrderCount: skippedOrders.length,
|
||||
skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
orderResultSummary: summarizeArrayForLog(orderResults),
|
||||
stockLockSummary: summarizeArrayForLog(Array.from(stockAllocationMap.entries()).map(([ stockId, quantity ]) => ({
|
||||
stock_id: stockId,
|
||||
locked_quantity: quantity,
|
||||
})),
|
||||
storageLockSummary: Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({
|
||||
}))),
|
||||
storageLockSummary: summarizeArrayForLog(Array.from(storageAllocationMap.entries()).map(([ storageId, quantity ]) => ({
|
||||
storage_id: storageId,
|
||||
locked_quantity: quantity,
|
||||
})),
|
||||
}))),
|
||||
});
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 事务提交完成', {
|
||||
warehouseId,
|
||||
pendingOrderIds,
|
||||
skippedOrders,
|
||||
orderResults,
|
||||
pendingOrderCount: pendingOrderIds.length,
|
||||
pendingOrderSampleIds: pendingOrderIds.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
skippedOrderCount: skippedOrders.length,
|
||||
skippedOrderSample: skippedOrders.slice(0, ALLOCATION_LOG_SAMPLE_LIMIT),
|
||||
orderResultSummary: summarizeArrayForLog(orderResults),
|
||||
});
|
||||
|
||||
const errorOrderResults = orderResults.filter(item => item.status === 'error');
|
||||
@ -1260,7 +1327,18 @@ class OrderStorageAllocationService extends MainService {
|
||||
message: shortageMessages.length > 0
|
||||
? '储位分配完成,部分订单库存不足'
|
||||
: '储位分配完成',
|
||||
responseData,
|
||||
responseDataSummary: {
|
||||
requestedOrderIds: summarizeArrayForLog(responseData.requested_order_ids),
|
||||
pendingOrderIds: summarizeArrayForLog(responseData.pending_order_ids),
|
||||
allocatedOrderIds: summarizeArrayForLog(responseData.allocated_order_ids),
|
||||
shortageOrderIds: summarizeArrayForLog(responseData.shortage_order_ids),
|
||||
skippedOrders: summarizeArrayForLog(responseData.skipped_orders),
|
||||
orders: summarizeArrayForLog(responseData.orders),
|
||||
stockLockSummary: summarizeArrayForLog(responseData.stock_lock_summary),
|
||||
storageLockSummary: summarizeArrayForLog(responseData.storage_lock_summary),
|
||||
shortageMessages: summarizeArrayForLog(responseData.shortage_messages),
|
||||
pickingCount: responseData.picking_count,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
329
app/service/systems/pick.js
Normal file
329
app/service/systems/pick.js
Normal file
@ -0,0 +1,329 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const REVIEWED_INSPECTION_STATUS = 'fin';
|
||||
|
||||
class PickSystemService extends Service {
|
||||
/**
|
||||
* 按仓库获取订单分表模型。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Object|null>} 订单模型对象。
|
||||
*/
|
||||
async getOrderModel(warehouseId) {
|
||||
const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||||
throw this.createBusinessError('订单分表模型工厂不可用', 500);
|
||||
}
|
||||
|
||||
const model = await factory.getCurrentModel(warehouseId);
|
||||
if (!model || typeof model.findOne !== 'function' || typeof model.findAll !== 'function') {
|
||||
throw this.createBusinessError('订单分表模型不可用', 500);
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带业务状态码的错误对象。
|
||||
*
|
||||
* @param {string} message 错误文案。
|
||||
* @param {number} [code=400] 错误码。
|
||||
* @return {Error} 错误对象。
|
||||
*/
|
||||
createBusinessError(message, code = 400) {
|
||||
const error = new Error(message);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析订单所属波次信息。
|
||||
*
|
||||
* @param {Object} order 订单记录。
|
||||
* @return {{waveId: number, waveNo: string}} 波次信息。
|
||||
*/
|
||||
resolveWaveInfo(order = {}) {
|
||||
const waveId = Number(order.wave_id || 0);
|
||||
const waveNo = String(order.wave_no || '').trim();
|
||||
return {
|
||||
waveId: Number.isFinite(waveId) ? waveId : 0,
|
||||
waveNo,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断订单是否已复核。
|
||||
*
|
||||
* 当前使用 `inspection_status === "fin"` 作为已复核判定。
|
||||
*
|
||||
* @param {Object} order 订单记录。
|
||||
* @return {boolean} 是否已复核。
|
||||
*/
|
||||
isOrderReviewed(order = {}) {
|
||||
return String(order.inspection_status || '').trim() === REVIEWED_INSPECTION_STATUS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据波次信息构建订单查询条件。
|
||||
*
|
||||
* @param {Object} waveInfo 波次信息。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Object} Sequelize 查询条件。
|
||||
*/
|
||||
buildWaveOrderWhere(waveInfo = {}, warehouseId) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const where = {
|
||||
warehouse_id: warehouseId,
|
||||
};
|
||||
|
||||
if (waveInfo.waveId > 0 && waveInfo.waveNo) {
|
||||
where[Op.or] = [
|
||||
{ wave_id: waveInfo.waveId },
|
||||
{ wave_no: waveInfo.waveNo },
|
||||
];
|
||||
return where;
|
||||
}
|
||||
|
||||
if (waveInfo.waveId > 0) {
|
||||
where.wave_id = waveInfo.waveId;
|
||||
return where;
|
||||
}
|
||||
|
||||
where.wave_no = waveInfo.waveNo;
|
||||
return where;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按波次信息查询拣货汇总。
|
||||
*
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {number} params.orderId 当前订单ID。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @param {string} [params.waveNo] 波次号。
|
||||
* @param {number} [params.waveId] 波次ID。
|
||||
* @param {number} [params.storeId] 货主ID。
|
||||
* @param {boolean} params.fullDisplay 是否完整显示。
|
||||
* @return {Promise<Object>} 波次拣货汇总结果。
|
||||
*/
|
||||
async queryPickingInfo(params = {}) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const { ctx } = this;
|
||||
const {
|
||||
orderId,
|
||||
warehouseId,
|
||||
waveNo,
|
||||
waveId,
|
||||
storeId,
|
||||
fullDisplay,
|
||||
} = params;
|
||||
|
||||
const normalizedOrderId = Number(orderId || 0);
|
||||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||||
throw this.createBusinessError('order_id 参数不合法', 400);
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||||
}
|
||||
|
||||
const waveInfo = {
|
||||
waveId: Number(waveId || 0),
|
||||
waveNo: String(waveNo || '').trim(),
|
||||
};
|
||||
if (waveInfo.waveId <= 0 && !waveInfo.waveNo) {
|
||||
throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400);
|
||||
}
|
||||
|
||||
const orderModel = await this.getOrderModel(normalizedWarehouseId);
|
||||
|
||||
const waveOrderRows = await orderModel.findAll({
|
||||
where: this.buildWaveOrderWhere(waveInfo, normalizedWarehouseId),
|
||||
attributes: [ 'id', 'inspection_status', 'store_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderIds = Array.isArray(waveOrderRows)
|
||||
? waveOrderRows
|
||||
.map(item => Number(item && item.id || 0))
|
||||
.filter(id => id > 0)
|
||||
: [];
|
||||
|
||||
if (orderIds.length === 0) {
|
||||
throw this.createBusinessError('未找到波次对应订单', 404);
|
||||
}
|
||||
|
||||
const orderStatusMap = new Map();
|
||||
for (const row of waveOrderRows) {
|
||||
const id = Number(row && row.id || 0);
|
||||
if (id <= 0) {
|
||||
continue;
|
||||
}
|
||||
orderStatusMap.set(id, {
|
||||
inspection_status: String(row && row.inspection_status || '').trim(),
|
||||
});
|
||||
}
|
||||
|
||||
const pickingRows = await ctx.model.Picking.findAll({
|
||||
where: {
|
||||
order_id: {
|
||||
[Op.in]: orderIds,
|
||||
},
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const spaceIds = Array.isArray(pickingRows)
|
||||
? Array.from(new Set(pickingRows
|
||||
.map(item => Number(item && item.space_id || 0))
|
||||
.filter(id => id > 0)))
|
||||
: [];
|
||||
|
||||
const locationRows = spaceIds.length > 0
|
||||
? await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: spaceIds,
|
||||
},
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
attributes: [
|
||||
'id',
|
||||
'space_code',
|
||||
'custom_name',
|
||||
'custom_barcode',
|
||||
'zone_id',
|
||||
'space_status',
|
||||
'is_enabled',
|
||||
'pick_sequence',
|
||||
'pick_priority',
|
||||
],
|
||||
raw: true,
|
||||
})
|
||||
: [];
|
||||
|
||||
const locationMap = new Map();
|
||||
for (const location of Array.isArray(locationRows) ? locationRows : []) {
|
||||
const locationId = Number(location && location.id || 0);
|
||||
if (locationId > 0) {
|
||||
locationMap.set(locationId, location);
|
||||
}
|
||||
}
|
||||
|
||||
const currentStoreId = Number(storeId || (waveOrderRows[0] && waveOrderRows[0].store_id) || 0);
|
||||
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
|
||||
where: {
|
||||
store_id: currentStoreId,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'store_remask', 'warehouse_remask', 'auth_status', 'use_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const fullDisplayFlag = Boolean(fullDisplay);
|
||||
const allDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => {
|
||||
const currentOrderId = Number(row && row.order_id || 0);
|
||||
const orderStatus = orderStatusMap.get(currentOrderId) || { inspection_status: 'none' };
|
||||
const reviewed = this.isOrderReviewed(orderStatus);
|
||||
const spaceId = Number(row && row.space_id || 0);
|
||||
|
||||
return {
|
||||
id: Number(row && row.id || 0),
|
||||
order_id: currentOrderId,
|
||||
order_item_id: Number(row && row.order_item_id || 0),
|
||||
storage_id: Number(row && row.storage_id || 0),
|
||||
quantity: Number(row && row.quantity || 0),
|
||||
space_id: spaceId,
|
||||
space_name: String(row && row.space_name || ''),
|
||||
picking_status: String(row && row.status || ''),
|
||||
inspection_status: orderStatus.inspection_status,
|
||||
reviewed,
|
||||
location_space: locationMap.get(spaceId) || null,
|
||||
store_warehouse: storeWarehouse || null,
|
||||
};
|
||||
});
|
||||
|
||||
const pendingReviewDetails = allDetails.filter(item => !item.reviewed);
|
||||
const reviewedDetails = allDetails.filter(item => item.reviewed);
|
||||
const displayDetails = fullDisplayFlag ? allDetails : pendingReviewDetails;
|
||||
|
||||
const sumQuantity = rows => rows.reduce((sum, item) => sum + Number(item && item.quantity || 0), 0);
|
||||
|
||||
return {
|
||||
order_id: normalizedOrderId,
|
||||
wave_id: waveInfo.waveId,
|
||||
wave_no: waveInfo.waveNo,
|
||||
full_display: fullDisplayFlag,
|
||||
summary: {
|
||||
total_count: allDetails.length,
|
||||
pending_review_count: pendingReviewDetails.length,
|
||||
reviewed_count: reviewedDetails.length,
|
||||
quantity_total: sumQuantity(allDetails),
|
||||
display_count: displayDetails.length,
|
||||
display_quantity_total: sumQuantity(displayDetails),
|
||||
},
|
||||
list: displayDetails,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按订单ID查询其波次拣货信息。
|
||||
*
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {number} params.orderId 订单ID。
|
||||
* @param {number} params.warehouseId 仓库ID。
|
||||
* @param {boolean} params.fullDisplay 是否完整显示。
|
||||
* @return {Promise<Object>} 波次拣货汇总结果。
|
||||
*/
|
||||
async queryByOrder(params = {}) {
|
||||
const {
|
||||
orderId,
|
||||
warehouseId,
|
||||
fullDisplay,
|
||||
} = params;
|
||||
|
||||
const normalizedOrderId = Number(orderId || 0);
|
||||
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
|
||||
throw this.createBusinessError('order_id 参数不合法', 400);
|
||||
}
|
||||
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
|
||||
}
|
||||
|
||||
const orderModel = await this.getOrderModel(normalizedWarehouseId);
|
||||
|
||||
const order = await orderModel.findOne({
|
||||
where: {
|
||||
id: normalizedOrderId,
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'store_id', 'wave_no', 'wave_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!order) {
|
||||
throw this.createBusinessError('订单不存在', 404);
|
||||
}
|
||||
|
||||
const waveInfo = this.resolveWaveInfo(order);
|
||||
if (waveInfo.waveId <= 0 && !waveInfo.waveNo) {
|
||||
throw this.createBusinessError('订单未分配波次号,暂无拣货信息', 400);
|
||||
}
|
||||
|
||||
return await this.queryPickingInfo({
|
||||
orderId: normalizedOrderId,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
waveNo: waveInfo.waveNo,
|
||||
waveId: waveInfo.waveId,
|
||||
storeId: Number(order.store_id || 0),
|
||||
fullDisplay,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PickSystemService;
|
||||
@ -13,27 +13,14 @@ class PoloApiService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 Polo API 请求并返回请求结果。
|
||||
* 发起 Polo API POST 请求。
|
||||
*
|
||||
* @param platid
|
||||
* @return {Promise<any>} request() 的返回结果。
|
||||
* @param {string} method 接口方法名。
|
||||
* @param {object|string} [bizcontent={}] 业务参数。
|
||||
* @param {object} [config={}] 平台配置。
|
||||
* @param {string} [token] 可选 token。
|
||||
* @return {Promise<any>} 接口响应数据。
|
||||
*/
|
||||
async test(platid) {
|
||||
return this.client.request({
|
||||
method: 'Differ.JH.LogisticsPlatFeatures',
|
||||
platid,
|
||||
bizcontent: {},
|
||||
});
|
||||
}
|
||||
async GetWayBillCondition(platid) {
|
||||
return this.client.request({
|
||||
method: 'Differ.JH.Logistics.GetWayBillCondition',
|
||||
platid,
|
||||
bizcontent: {
|
||||
cpcode: 'POSTB',
|
||||
},
|
||||
});
|
||||
}
|
||||
async request(method, bizcontent = {}, config = {}, token) {
|
||||
console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent));
|
||||
return this.client.request({
|
||||
@ -43,6 +30,16 @@ class PoloApiService extends Service {
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起 Polo API GET 请求。
|
||||
*
|
||||
* @param {string} method 接口方法名。
|
||||
* @param {object|string} [bizcontent={}] 业务参数。
|
||||
* @param {object} [config={}] 平台配置。
|
||||
* @param {string} [token] 可选 token。
|
||||
* @return {Promise<any>} 接口响应数据。
|
||||
*/
|
||||
async get(method, bizcontent = {}, config = {}, token) {
|
||||
console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent));
|
||||
return this.client.get({
|
||||
|
||||
265
app/service/systems/setting/warehouse.js
Normal file
265
app/service/systems/setting/warehouse.js
Normal file
@ -0,0 +1,265 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
// 仓库设置字段元信息(对应 wms_store.subject_config)
|
||||
const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
Object.freeze({
|
||||
key: 'max_notice_webhook_count',
|
||||
name: '最大通知 Webhook 次数',
|
||||
type: 'integer',
|
||||
default: 5,
|
||||
required: false,
|
||||
description: '单次事件最多触发的 Webhook 通知次数(0-5)',
|
||||
min: 0,
|
||||
max: 5,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'max_wave_quantity',
|
||||
name: '仓库波次最大数量限制',
|
||||
type: 'integer',
|
||||
default: 500,
|
||||
required: false,
|
||||
description: '控制单个波次允许的最大订单数量,默认 500',
|
||||
min: 1,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'min_group_order_fetch_quantity',
|
||||
name: '最小团购订单抓取数量',
|
||||
type: 'integer',
|
||||
default: 13,
|
||||
required: false,
|
||||
description: '控制团购波次最小抓取订单数量,默认 13',
|
||||
min: 1,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'default_express_code',
|
||||
name: '默认快递编码',
|
||||
type: 'string',
|
||||
default: 'STO',
|
||||
required: false,
|
||||
description: '仓库默认使用的快递编码',
|
||||
maxLength: 50,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'default_platform_code',
|
||||
name: '默认平台编码',
|
||||
type: 'string',
|
||||
default: 'TB',
|
||||
required: false,
|
||||
description: '仓库默认使用的平台编码',
|
||||
maxLength: 50,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'group_wave_prefix',
|
||||
name: '团购波次前缀',
|
||||
type: 'string',
|
||||
default: 'B',
|
||||
required: false,
|
||||
description: '团购波次编号前缀,最多 5 个字符,默认 B',
|
||||
maxLength: 5,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'delete_order_wave_prefix',
|
||||
name: '删单波次前缀',
|
||||
type: 'string',
|
||||
default: 'A',
|
||||
required: false,
|
||||
description: '删单波次编号前缀,最多 5 个字符,默认 A',
|
||||
maxLength: 5,
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'webhook_enabled',
|
||||
name: '是否启用 Webhook',
|
||||
type: 'flag',
|
||||
default: false,
|
||||
required: false,
|
||||
description: '控制仓库是否启用 Webhook 事件推送',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'callback_strategy',
|
||||
name: '回调策略',
|
||||
type: 'enum',
|
||||
default: 'async',
|
||||
required: false,
|
||||
description: '仓库 Webhook 事件的回调执行策略',
|
||||
options: [
|
||||
Object.freeze({ value: 'sync', label: '同步回调' }),
|
||||
Object.freeze({ value: 'async', label: '异步回调' }),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
|
||||
class SettingWarehouseService extends Service {
|
||||
createError(message, code = 500) {
|
||||
const error = new Error(message);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 ctx.user.store_id 获取当前仓库 ID。
|
||||
*
|
||||
* @return {number} 仓库 ID。
|
||||
* @throws {Error} 未识别到仓库时抛出,状态码 400。
|
||||
*/
|
||||
getCurrentWarehouseId() {
|
||||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw this.createError('未识别到当前仓库,无法操作仓库设置', 400);
|
||||
}
|
||||
return warehouseId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定缓存键。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async deleteCacheByKey(cacheKey) {
|
||||
if (!cacheKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.app && typeof this.app.delCacheAsync === 'function') {
|
||||
await this.app.delCacheAsync(cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
await this.app.setCacheAsync(cacheKey, null, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定仓库设置相关缓存。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async clearWarehouseSettingCache(warehouseId) {
|
||||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = [
|
||||
`delivery_order:store:${normalizedWarehouseId}:subject_config`,
|
||||
`warehouse:${normalizedWarehouseId}store:${normalizedWarehouseId}:info`,
|
||||
];
|
||||
|
||||
await Promise.all(keys.map(key => this.deleteCacheByKey(key).catch(() => null)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库设置字段元信息列表。
|
||||
*
|
||||
* @return {Array} 字段元信息数组(浅拷贝,含 options 拷贝)。
|
||||
*/
|
||||
getFieldMeta() {
|
||||
return WAREHOUSE_SETTING_FIELDS.map(field => ({
|
||||
key: field.key,
|
||||
name: field.name,
|
||||
type: field.type,
|
||||
default: field.default,
|
||||
required: field.required,
|
||||
description: field.description,
|
||||
...(Array.isArray(field.options) ? { options: field.options.map(o => ({ ...o })) } : {}),
|
||||
...(field.min !== undefined ? { min: field.min } : {}),
|
||||
...(field.max !== undefined ? { max: field.max } : {}),
|
||||
...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取当前仓库的设置(wms_store.subject_config)。
|
||||
*
|
||||
* @return {Promise<Object>} 包含 warehouse_id 与 subject_config 的对象。
|
||||
* @throws {Error} 仓库不存在时抛出,状态码 404。
|
||||
*/
|
||||
async getSettings() {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
const store = await this.ctx.model.Store.findByPk(warehouseId, {
|
||||
attributes: [ 'id', 'subject_config' ],
|
||||
});
|
||||
|
||||
if (!store) {
|
||||
throw this.createError('仓库不存在', 404);
|
||||
}
|
||||
|
||||
return {
|
||||
warehouse_id: warehouseId,
|
||||
subject_config: store.subject_config,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改当前仓库设置并清理指定仓库缓存。
|
||||
*
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @param {Object} [data.subject_config] 仓库设置对象,支持部分字段更新。
|
||||
* @param {number|string} [data.cache_warehouse_id] 需要清理缓存的仓库 ID,默认当前仓库。
|
||||
* @param {number|string} [data.cacheWarehouseId] 同 cache_warehouse_id。
|
||||
* @return {Promise<Object>} 更新后的仓库设置。
|
||||
*/
|
||||
async saveSettings(data = {}) {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
const storeModel = this.ctx.model && this.ctx.model.Store;
|
||||
|
||||
if (!storeModel || typeof storeModel.findByPk !== 'function') {
|
||||
throw this.createError('Store model 不可用', 500);
|
||||
}
|
||||
|
||||
const store = await storeModel.findByPk(warehouseId, {
|
||||
attributes: [ 'id', 'subject_config' ],
|
||||
});
|
||||
|
||||
if (!store) {
|
||||
throw this.createError('仓库不存在', 404);
|
||||
}
|
||||
|
||||
const hasSubjectConfig = Object.prototype.hasOwnProperty.call(data || {}, 'subject_config');
|
||||
const nextPatch = hasSubjectConfig ? data.subject_config : null;
|
||||
if (!nextPatch || typeof nextPatch !== 'object' || Array.isArray(nextPatch)) {
|
||||
throw this.createError('subject_config 参数不能为空且必须是对象', 400);
|
||||
}
|
||||
|
||||
const mergedConfig = {
|
||||
...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}),
|
||||
...nextPatch,
|
||||
};
|
||||
|
||||
let normalizedConfig;
|
||||
try {
|
||||
normalizedConfig = typeof storeModel.normalizeSubjectConfig === 'function'
|
||||
? storeModel.normalizeSubjectConfig(mergedConfig)
|
||||
: mergedConfig;
|
||||
} catch (error) {
|
||||
throw this.createError(error.message || 'subject_config 参数不合法', Number(error.code) || 400);
|
||||
}
|
||||
|
||||
await store.update({
|
||||
subject_config: normalizedConfig,
|
||||
});
|
||||
|
||||
let cacheWarehouseId = Number(
|
||||
data.cache_warehouse_id !== undefined ? data.cache_warehouse_id : (data.cacheWarehouseId !== undefined ? data.cacheWarehouseId : warehouseId)
|
||||
);
|
||||
if (!Number.isFinite(cacheWarehouseId) || cacheWarehouseId <= 0) {
|
||||
throw this.createError('cache_warehouse_id 参数不合法', 400);
|
||||
}
|
||||
cacheWarehouseId = Math.floor(cacheWarehouseId);
|
||||
|
||||
await this.clearWarehouseSettingCache(cacheWarehouseId);
|
||||
|
||||
return {
|
||||
warehouse_id: warehouseId,
|
||||
subject_config: store.subject_config,
|
||||
cache_cleared_warehouse_id: cacheWarehouseId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingWarehouseService;
|
||||
@ -2310,6 +2310,20 @@ class stockStoreService extends Service {
|
||||
if (!stock_info) {
|
||||
throw new Error('商品不存在');
|
||||
}
|
||||
|
||||
const hasInputItemCode = Object.prototype.hasOwnProperty.call(data, 'item_code');
|
||||
if (hasInputItemCode) {
|
||||
const itemCodeUniqueResult = await this.checkItemCodeUnique(
|
||||
id,
|
||||
item_code,
|
||||
stock_info.store_id,
|
||||
stock_info.warehouse_id
|
||||
);
|
||||
if (!itemCodeUniqueResult || !itemCodeUniqueResult.isUnique) {
|
||||
throw new Error('商品编码已存在,请检查后重试');
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 准备更新数据
|
||||
const updateData = {
|
||||
item_code,
|
||||
@ -2529,42 +2543,45 @@ class stockStoreService extends Service {
|
||||
async stockLog() {
|
||||
return undefined;
|
||||
}
|
||||
async checkItemCodeUnique(id, item_code, store_id, warehouse_id) {
|
||||
/**
|
||||
* 校验商品编码在指定仓库与货主维度下是否唯一。
|
||||
* @param {number|null} item_id 商品ID(编辑场景用于排除自身)
|
||||
* @param {string} item_code 商品编码
|
||||
* @param {number} owner_id 货主ID
|
||||
* @param {number} warehouse_id 仓库ID
|
||||
* @return {Promise<{unique:boolean,isUnique:boolean,message?:string}>} 唯一性校验结果
|
||||
*/
|
||||
async checkItemCodeUnique(item_id, item_code, owner_id, warehouse_id) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = this.app.Sequelize || app.Sequelize;
|
||||
try {
|
||||
// 检查条码是否被其他仓位使用(排除当前仓位)
|
||||
let whereId = null;
|
||||
if (id) {
|
||||
whereId = {
|
||||
id: {
|
||||
[Op.ne]: id, // 排除当前仓位ID
|
||||
},
|
||||
const normalizedItemCode = String(item_code || '').trim();
|
||||
const where = {
|
||||
item_code: normalizedItemCode,
|
||||
store_id: owner_id,
|
||||
warehouse_id,
|
||||
deleted_at: null,
|
||||
};
|
||||
|
||||
if (item_id) {
|
||||
where.id = {
|
||||
[Op.ne]: item_id,
|
||||
};
|
||||
}
|
||||
const where = {
|
||||
[Op.and]: [
|
||||
whereId,
|
||||
{ item_code },
|
||||
{ store_id },
|
||||
{ warehouse_id },
|
||||
{ deleted_at: null }, // 未删除的记录
|
||||
],
|
||||
};
|
||||
|
||||
const space = await ctx.model.StockWarehouse.findOne({
|
||||
where,
|
||||
attributes: [ 'id' ],
|
||||
});
|
||||
|
||||
// 如果没有找到重复的条码,返回唯一
|
||||
if (!space) {
|
||||
return { isUnique: true };
|
||||
return { unique: true, isUnique: true };
|
||||
}
|
||||
return { isUnique: false, message: '商品编码已被使用' };
|
||||
return { unique: false, isUnique: false, message: '商品编码已存在' };
|
||||
|
||||
} catch (error) {
|
||||
ctx.logger.error('检查商品编码唯一性失败:', error);
|
||||
return { isUnique: false, message: '商品编码检测失败' };
|
||||
return { unique: false, isUnique: false, message: '商品编码检测失败' };
|
||||
}
|
||||
}
|
||||
async handleBatchDelete(data) {
|
||||
|
||||
@ -172,42 +172,7 @@ class IndexService extends Service {
|
||||
* @return {Promise<Object>} 更新后的库存记录。
|
||||
*/
|
||||
async lockQuantity(id, quantity, options = {}) {
|
||||
const callContext = {
|
||||
hasTransaction: Boolean(options && options.transaction),
|
||||
source: options && (options.source || options.caller || options.from || options.action) || null,
|
||||
optionKeys: options && typeof options === 'object'
|
||||
? Object.keys(options).filter(key => key !== 'transaction')
|
||||
: [],
|
||||
};
|
||||
|
||||
console.log('[StorageService.lockQuantity] 开始锁定库存', {
|
||||
id,
|
||||
quantity,
|
||||
callContext,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await this.updateQuantity(id, 0, quantity, options);
|
||||
|
||||
console.log('[StorageService.lockQuantity] 锁定库存成功', {
|
||||
id,
|
||||
quantity,
|
||||
callContext,
|
||||
storageId: result && result.id,
|
||||
locked_quantity: result && result.locked_quantity,
|
||||
available_quantity: result && result.available_quantity,
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.log('[StorageService.lockQuantity] 锁定库存失败', {
|
||||
id,
|
||||
quantity,
|
||||
callContext,
|
||||
error,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
return await this.updateQuantity(id, 0, quantity, options);
|
||||
}
|
||||
|
||||
async unlockQuantity(id, quantity, options = {}) {
|
||||
|
||||
@ -416,21 +416,24 @@ class ReceivingService extends Service {
|
||||
|
||||
// 批量记录操作日志
|
||||
try {
|
||||
await Promise.all(ids.map(receivingId =>
|
||||
ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'receiving',
|
||||
businessId: receivingId,
|
||||
operationCode: 'RECEIVING_BATCH_CANCEL',
|
||||
operator: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id,
|
||||
name: ctx.user?.employees_name || '',
|
||||
},
|
||||
extras: {
|
||||
warehouseId: warehouse_id,
|
||||
},
|
||||
beforeChanges: null,
|
||||
})
|
||||
));
|
||||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
const payloads = ids.map(receivingId => ({
|
||||
businessType: 'receiving',
|
||||
businessId: receivingId,
|
||||
operationCode: 'RECEIVING_BATCH_CANCEL',
|
||||
operator: {
|
||||
id: ctx.user?.employees_id || ctx.user?.id,
|
||||
name: ctx.user?.employees_name || '',
|
||||
},
|
||||
extras: {
|
||||
warehouseId: warehouse_id,
|
||||
},
|
||||
beforeChanges: null,
|
||||
}));
|
||||
|
||||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
await operationLogService.createOperationLogs(payloads);
|
||||
}
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn('[receiving.batchCancelReceiving] 写入操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
@ -500,22 +503,25 @@ class ReceivingService extends Service {
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.all(ids.map(receivingId =>
|
||||
ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'receiving',
|
||||
businessId: receivingId,
|
||||
operationCode: 'RECEIVING_REJECT',
|
||||
operator: {
|
||||
id: reviewerEmployeeId || ctx.user?.id,
|
||||
name: reviewerName,
|
||||
},
|
||||
extras: {
|
||||
warehouseId: warehouse_id,
|
||||
remark: updateData.remark || '',
|
||||
},
|
||||
beforeChanges: null,
|
||||
})
|
||||
));
|
||||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
const payloads = ids.map(receivingId => ({
|
||||
businessType: 'receiving',
|
||||
businessId: receivingId,
|
||||
operationCode: 'RECEIVING_REJECT',
|
||||
operator: {
|
||||
id: reviewerEmployeeId || ctx.user?.id,
|
||||
name: reviewerName,
|
||||
},
|
||||
extras: {
|
||||
warehouseId: warehouse_id,
|
||||
remark: updateData.remark || '',
|
||||
},
|
||||
beforeChanges: null,
|
||||
}));
|
||||
|
||||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
await operationLogService.createOperationLogs(payloads);
|
||||
}
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn('[receiving.rejectReceiving] 写入操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
@ -566,7 +572,7 @@ class ReceivingService extends Service {
|
||||
`收货单ID:${item.id || ''}`,
|
||||
`收货单号:${item.receiving_number || '无'}`,
|
||||
`收货创建人:${item.creator && item.creator.name || '无'}`,
|
||||
`请及时处理重新提交完成收货。`,
|
||||
'请及时处理重新提交完成收货。',
|
||||
].join('\n') + '。',
|
||||
businessId: item.id || ids[0],
|
||||
subject: {
|
||||
@ -700,19 +706,23 @@ class ReceivingService extends Service {
|
||||
|
||||
// 写操作日志(失败不影响业务)
|
||||
try {
|
||||
await Promise.all(normalizedIds.map(receivingId =>
|
||||
ctx.service.systems.operationLog.createOperationLog({
|
||||
businessType: 'receiving',
|
||||
businessId: receivingId,
|
||||
operationCode: 'RECEIVING_REVIEW',
|
||||
operator: {
|
||||
id: reviewerEmployeeId || ctx.user?.id,
|
||||
name: reviewerName || '',
|
||||
},
|
||||
extras: { warehouseId: warehouse_id },
|
||||
beforeChanges: null,
|
||||
})
|
||||
));
|
||||
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
|
||||
const payloads = normalizedIds.map(receivingId => ({
|
||||
businessType: 'receiving',
|
||||
businessId: receivingId,
|
||||
operationCode: 'RECEIVING_REVIEW',
|
||||
operator: {
|
||||
id: reviewerEmployeeId || ctx.user?.id,
|
||||
name: reviewerName || '',
|
||||
},
|
||||
extras: { warehouseId: warehouse_id },
|
||||
beforeChanges: null,
|
||||
transaction,
|
||||
}));
|
||||
|
||||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
await operationLogService.createOperationLogs(payloads, { transaction });
|
||||
}
|
||||
} catch (logErr) {
|
||||
ctx.logger.warn('[receiving.reviewReceiving] 写入操作日志失败,不影响业务', logErr);
|
||||
}
|
||||
|
||||
@ -27,13 +27,13 @@ module.exports = appInfo => {
|
||||
clients: {
|
||||
cache: {
|
||||
port: 6379,
|
||||
host: '112.124.21.102',
|
||||
host: '127.0.0.1',
|
||||
password: 'qwe2019@',
|
||||
db: 10,
|
||||
},
|
||||
printer: {
|
||||
port: 6379,
|
||||
host: '112.124.21.102',
|
||||
host: '127.0.0.1',
|
||||
password: 'qwe2019@',
|
||||
db: 11,
|
||||
},
|
||||
@ -135,14 +135,14 @@ module.exports = appInfo => {
|
||||
config.mysql = {
|
||||
clients: {
|
||||
wms: {
|
||||
host: '112.124.21.102',
|
||||
host: '127.0.0.1',
|
||||
port: '3306',
|
||||
user: 'wms',
|
||||
password: 'P6j3YTHTpirepYWz',
|
||||
database: 'wms',
|
||||
},
|
||||
ye4s: {
|
||||
host: '112.124.21.102',
|
||||
host: '127.0.0.1',
|
||||
port: '3306',
|
||||
user: 'ye4s',
|
||||
password: 'H@8h^QE4N$L.F_*',
|
||||
|
||||
@ -53,11 +53,24 @@ function resolveMysqlClient(appConfig, clientName) {
|
||||
}
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js'));
|
||||
const localConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const appConfig = mergeDeep(defaultConfig, localConfig);
|
||||
const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms';
|
||||
const mysqlClient = resolveMysqlClient(appConfig, clientName);
|
||||
|
||||
let mysqlClient;
|
||||
if (process.env.DB_HOST) {
|
||||
mysqlClient = {
|
||||
host: process.env.DB_HOST,
|
||||
port: process.env.DB_PORT || 3306,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME || 'wms',
|
||||
};
|
||||
} else {
|
||||
const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js'));
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const localConfig = isProduction ? {} : loadEggConfig(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const appConfig = mergeDeep(defaultConfig, localConfig);
|
||||
const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms';
|
||||
mysqlClient = resolveMysqlClient(appConfig, clientName);
|
||||
}
|
||||
|
||||
const baseConfig = {
|
||||
username: mysqlClient.user,
|
||||
|
||||
109
database/migrations/20260504000000-baseline.js
Normal file
109
database/migrations/20260504000000-baseline.js
Normal file
@ -0,0 +1,109 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* Baseline migration - 2026-05-04
|
||||
* 以 SequelizeMeta.sql 为基准,定义当前数据库完整结构。
|
||||
* 生产环境:请将本文件名插入 SequelizeMeta 表,标记为已执行。
|
||||
* 新环境:直接运行 db:migrate,本文件会创建所有表结构。
|
||||
*/
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
const sqlRaw = fs.readFileSync(
|
||||
path.join(__dirname, '../../SequelizeMeta.sql'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
// 预处理:去掉 DROP TABLE,改为 CREATE TABLE IF NOT EXISTS,跳过 SequelizeMeta 表
|
||||
const sql = sqlRaw
|
||||
.replace(/SET NAMES utf8mb4;\r?\n/g, '')
|
||||
.replace(/DROP TABLE IF EXISTS `SequelizeMeta`;\r?\nCREATE TABLE[\s\S]*?ROW_FORMAT = Dynamic;\r?\n/m, '')
|
||||
.replace(/DROP TABLE IF EXISTS `[^`]+`;\r?\n/g, '')
|
||||
.replace(/CREATE TABLE `/g, 'CREATE TABLE IF NOT EXISTS `')
|
||||
.replace(/SET FOREIGN_KEY_CHECKS = 1;?/g, '');
|
||||
|
||||
// 按分号+换行切割,逐条执行
|
||||
const statements = sql
|
||||
.split(/;\s*\r?\n/)
|
||||
.map(s => s.trim())
|
||||
.filter(s => s && !s.startsWith('--') && !s.startsWith('/*') && s !== 'SET FOREIGN_KEY_CHECKS = 0');
|
||||
|
||||
// 先禁用外键检查
|
||||
await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
|
||||
for (const stmt of statements) {
|
||||
if (stmt) {
|
||||
await queryInterface.sequelize.query(stmt + ';');
|
||||
}
|
||||
}
|
||||
await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
|
||||
// 按外键依赖逆序删除
|
||||
const tables = [
|
||||
'wms_account_platform_active',
|
||||
'wms_employee_role',
|
||||
'wms_wave_batch',
|
||||
'wms_picking',
|
||||
'wms_picking_strategy',
|
||||
'wms_operation_log',
|
||||
'wms_notification_send_log',
|
||||
'wms_notification_webhook',
|
||||
'wms_stock_transaction',
|
||||
'wms_storage',
|
||||
'wms_receiving_detail',
|
||||
'wms_receiving',
|
||||
'wms_order_express_print_data',
|
||||
'wms_order_express',
|
||||
'wms_entry_items',
|
||||
'wms_entry_order',
|
||||
'wms_file_reference',
|
||||
'wms_file',
|
||||
'wms_i18n_translations',
|
||||
'wms_i18n_keys',
|
||||
'wms_express_print_record',
|
||||
'wms_print_log',
|
||||
'wms_express_interface',
|
||||
'wms_express_setting',
|
||||
'wms_embargo_policies',
|
||||
'wms_prohibited_type',
|
||||
'wms_location_space',
|
||||
'wms_location_zone',
|
||||
'wms_location_type',
|
||||
'wms_print_station_express',
|
||||
'wms_print_stations',
|
||||
'wms_print_template',
|
||||
'wms_platform_print_config',
|
||||
'wms_print_record',
|
||||
'wms_print_computer',
|
||||
'wms_print_items',
|
||||
'wms_print_log',
|
||||
'wms_system_log',
|
||||
'wms_stock_unit',
|
||||
'wms_stock_warehouse',
|
||||
'wms_stock_store',
|
||||
'wms_api_app',
|
||||
'wms_interface_type',
|
||||
'wms_account_store_employee',
|
||||
'wms_role',
|
||||
'wms_permission',
|
||||
'wms_platfrom_setting',
|
||||
'wms_fast_where',
|
||||
'wms_qimen_log',
|
||||
'wms_qimen_apps',
|
||||
'wms_express_product_type',
|
||||
'wms_express',
|
||||
'wms_account_login_log',
|
||||
'wms_store_warehouse',
|
||||
'wms_store',
|
||||
'wms_account',
|
||||
];
|
||||
for (const table of tables) {
|
||||
await queryInterface.sequelize.query(`DROP TABLE IF EXISTS \`${table}\``);
|
||||
}
|
||||
await queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
|
||||
},
|
||||
};
|
||||
@ -127,6 +127,7 @@
|
||||
| items_hash | string | MD5哈希值(32位) | 商品明细哈希 |
|
||||
| items_crc | number | CRC32校验码 | 商品明细校验码 |
|
||||
| wave_id | number | 波次ID | 0 表示未分配 |
|
||||
| wave_no | string | 波次号 | 空字符串表示未分配 |
|
||||
| post_status | enum | 分配快递号状态机 | padding=处理中,fin=完成,timeout=超时,error=失败,none=未开始 |
|
||||
| storage_status | enum | 分配储位状态机 | padding=处理中,fin=完成,error=失败,none=未开始 |
|
||||
| pick_status | enum | 拣货状态机 | padding=处理中,fin=完成,error=失败,none=未开始 |
|
||||
|
||||
@ -1,40 +1,192 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.04.22-system-02",
|
||||
"date": "2026-04-22",
|
||||
"summary": "新增 order.pendingOrder.syncOrderIds:待处理订单同步透传入口",
|
||||
"methods": [
|
||||
"order.pendingOrder.syncOrderIds"
|
||||
],
|
||||
"notes": [
|
||||
"新增 order.pendingOrder.syncOrderIds:仅接收 order_ids 并转发到服务层,当前不做业务处理。",
|
||||
"接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。",
|
||||
"该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.04.22-system-01",
|
||||
"date": "2026-04-22",
|
||||
"summary": "补全订单工作台各模块 detail 方法文档",
|
||||
"methods": [
|
||||
"order.detail",
|
||||
"order.pendingOrder.detail",
|
||||
"order.reviewOrder.detail",
|
||||
"order.expectionOrder.detail",
|
||||
"order.outboundOrder.detail",
|
||||
"order.deliveryOrder.detail",
|
||||
"order.deliveryExpectionOrder.detail",
|
||||
"order.entrustOrder.detail",
|
||||
"order.archiveOrder.detail"
|
||||
],
|
||||
"notes": [
|
||||
"补全文档:detail 为订单工作台通用详情方法,入参支持 ids/id/order_id/orderId;可选 tableType/tablePosition/type/moduleName,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等。",
|
||||
"返回包含 order/detail(订单头)、orderItems/items(商品明细)、expresses(运单信息)、waybill_codes(去重运单号数组)。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
{
|
||||
"version": "2026.05.05-system-02",
|
||||
"date": "2026-05-05",
|
||||
"summary": "order.wave.batchList:新增 where.storage_assignment_status 的过滤语义说明",
|
||||
"methods": [
|
||||
"order.wave.batchList"
|
||||
],
|
||||
"notes": [
|
||||
"新增 where 字段 `storage_assignment_status`:类型 string,可选值:`未分配`、`部分分配`、`已分配`;默认不传:不做分配状态限制。",
|
||||
"过滤语义:`已分配`:聚合后全部 fin;`部分分配`:不含 error,且既不是全 none,也不是全 fin;`未分配`:全 none 或包含 error(异常并入未分配筛选集合)。",
|
||||
"说明:返回字段 `storage_assignment_status` 的展示值保持不变;包含 error 时仍可能展示“分配异常”,但 where 的过滤语义把异常算到“未分配”集合,避免把过滤语义与展示值混淆。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.05-system-01",
|
||||
"date": "2026-05-05",
|
||||
"summary": "新增 order.wave.singleOrderFetchList:散单候选分组查询(排除团购命中分组)",
|
||||
"methods": [
|
||||
"order.wave.singleOrderFetchList"
|
||||
],
|
||||
"notes": [
|
||||
"新增 order.wave.singleOrderFetchList:返回按机器结构分组的散单候选列表,接口会排除已达团购阈值(同组订单数量 >= same_order_quantity 或仓库配置 min_group_order_fetch_quantity)的分组,仅返回同组订单数量 < 阈值 的分组(散单候选)。",
|
||||
"与 order.wave.groupOrderFetchList 的关键差异:groupOrderFetchList 返回满足团购阈值(>=)的分组;singleOrderFetchList 返回未达阈值(<)的散单候选分组。",
|
||||
"影响范围:订单波次抓取相关前端/调度服务。兼容性:不影响或修改现有 order.wave.groupOrderFetchList,两个接口可并行使用。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.04-system-04",
|
||||
"date": "2026-05-04",
|
||||
"summary": "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述",
|
||||
"methods": [
|
||||
"stock.warehouse.checkItemCodeUnique"
|
||||
],
|
||||
"notes": [
|
||||
"完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述"
|
||||
],
|
||||
"type": "modified"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.04-system-03",
|
||||
"date": "2026-05-04",
|
||||
"summary": "新增订单打印模块:按波次IDs获取打印数据并自动过滤未完全分配波次",
|
||||
"methods": [
|
||||
"order.print.getWavePrintData"
|
||||
],
|
||||
"notes": [
|
||||
"按波次IDs获取订单打印数据,内部去重并规范化 wave_ids,自动过滤快递未完全分配的波次;返回通过过滤的波次订单明细,按 wave_no 排序分组,并在 ext 中返回 missing_wave_ids 与 filtered_wave_ids。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.04-system-02",
|
||||
"date": "2026-05-04",
|
||||
"summary": "修改 pick.query 入参:order_id -> waybill_code",
|
||||
"methods": [
|
||||
"pick.query"
|
||||
],
|
||||
"notes": [
|
||||
"入参从 order_id 改为 waybill_code(快递号),通过快递号查找订单后再查波次拣货信息"
|
||||
],
|
||||
"type": "breaking_change"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.04-system-01",
|
||||
"date": "2026-05-04",
|
||||
"summary": "新增 system method pick.query:按订单查询波次拣货信息",
|
||||
"methods": [
|
||||
"pick.query"
|
||||
],
|
||||
"notes": [
|
||||
"按订单查询该订单所属波次的拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-09",
|
||||
"date": "2026-05-03",
|
||||
"summary": "新增按 request_id 查询分配状态/结果接口",
|
||||
"methods": [
|
||||
"order.pendingOrder.allocateStorageProgress"
|
||||
],
|
||||
"notes": [
|
||||
"新增按 request_id 查询储位分配异步任务状态/结果接口,支持 status:submitted/running/success/failed/not_found;success 返回 result(底层分配结果),failed 返回 error(错误信息);兼容 requestId 参数名。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-07",
|
||||
"date": "2026-05-03",
|
||||
"summary": "新增抓取进度查询接口",
|
||||
"methods": [
|
||||
"order.wave.fetch",
|
||||
"order.wave.fetchTaskProgress"
|
||||
],
|
||||
"notes": [
|
||||
"新增按 task_id 查询抓取任务进度的接口 order.wave.fetchTaskProgress,支持返回 status(submitted/running/success/failed/not_found)及进度相关字段:progress_percent、finished_structure_count、total_fetched_quantity、duration_ms、error、update_time 等;同时明确 order.wave.fetch 为异步任务提交接口,客户端可通过 task_id 调用 order.wave.fetchTaskProgress 查询进度和最终结果。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-05",
|
||||
"date": "2026-05-03",
|
||||
"summary": "补齐仓库设置模块 setting.warehouse 的 methods 文档",
|
||||
"methods": [
|
||||
"setting.warehouse.getSettings",
|
||||
"setting.warehouse.getFieldMeta",
|
||||
"setting.warehouse.saveSettings"
|
||||
],
|
||||
"notes": [
|
||||
"补齐仓库配置 methods API 文档"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-04",
|
||||
"date": "2026-05-03",
|
||||
"summary": "order.wave:自动加团新增跳过规则并新增批量结束自动加团接口",
|
||||
"methods": [
|
||||
"order.wave.batchAutoGrouping",
|
||||
"order.wave.batchFinishAutoGrouping"
|
||||
],
|
||||
"notes": [
|
||||
"开启自动加团新增“已打印/超最大波次容量”跳过规则并在响应中返回跳过明细;新增批量结束自动加团接口(将 wave_status=0 的波次批量置为 1)"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-03",
|
||||
"date": "2026-05-03",
|
||||
"summary": "裁剪 order_list 以轻量化返回",
|
||||
"methods": [
|
||||
"order.wave.batchList"
|
||||
],
|
||||
"notes": [
|
||||
"移除响应中的 order_list 字段,接口仅返回波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-02",
|
||||
"date": "2026-05-03",
|
||||
"summary": "新增 order.wave.batchAutoGrouping:批量改为自动加团中",
|
||||
"methods": [
|
||||
"order.wave.batchAutoGrouping"
|
||||
],
|
||||
"notes": [
|
||||
"新增批量改为自动加团中接口及返回字段"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.04.22-system-02",
|
||||
"date": "2026-04-22",
|
||||
"summary": "新增 order.pendingOrder.syncOrderIds:待处理订单同步透传入口",
|
||||
"methods": [
|
||||
"order.pendingOrder.syncOrderIds"
|
||||
],
|
||||
"notes": [
|
||||
"新增 order.pendingOrder.syncOrderIds:仅接收 order_ids 并转发到服务层,当前不做业务处理。",
|
||||
"接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。",
|
||||
"该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.04.22-system-01",
|
||||
"date": "2026-04-22",
|
||||
"summary": "补全订单工作台各模块 detail 方法文档",
|
||||
"methods": [
|
||||
"order.detail",
|
||||
"order.pendingOrder.detail",
|
||||
"order.reviewOrder.detail",
|
||||
"order.expectionOrder.detail",
|
||||
"order.outboundOrder.detail",
|
||||
"order.deliveryOrder.detail",
|
||||
"order.deliveryExpectionOrder.detail",
|
||||
"order.entrustOrder.detail",
|
||||
"order.archiveOrder.detail"
|
||||
],
|
||||
"notes": [
|
||||
"补全文档:detail 为订单工作台通用详情方法,入参支持 ids/id/order_id/orderId;可选 tableType/tablePosition/type/moduleName,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等。",
|
||||
"返回包含 order/detail(订单头)、orderItems/items(商品明细)、expresses(运单信息)、waybill_codes(去重运单号数组)。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.04.19-system-01",
|
||||
"date": "2026-04-19",
|
||||
"summary": "新增方法 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 查询全字段列表并支持缓存",
|
||||
@ -953,5 +1105,99 @@
|
||||
"step 由货主策略 need_order_approval 决定(与 createOrder 一致);通过事务保证每个订单的主记录与明细原子写入。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.01-system-01",
|
||||
"date": "2026-05-01",
|
||||
"summary": "新增基础模块 IM 登录码接口文档:index.loginToIm",
|
||||
"methods": [
|
||||
"index.loginToIm"
|
||||
],
|
||||
"notes": [
|
||||
"新增 index.loginToIm 文档,入参为空对象({}),依赖当前登录用户上下文生成一次性 code。",
|
||||
"响应增加 data.code 字段,长度固定 64 位(hex),默认有效期 5 分钟。",
|
||||
"错误码补充:401(用户未登录)、400(用户信息不完整,缺 employees_id 或 employees_name)。",
|
||||
"该接口仅做登录码签发,实际换取员工信息由 IM 侧 ssoCodeToId 完成并在成功后使 code 失效。"
|
||||
],
|
||||
"type": "added"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.01-system-03",
|
||||
"date": "2026-05-01",
|
||||
"summary": "扩展 index.loginToIm 返回字段:增加主体/主体类型/头像信息",
|
||||
"methods": [
|
||||
"index.loginToIm"
|
||||
],
|
||||
"notes": [
|
||||
"登录码签发接口响应新增 employees_id、employees_name、subject、store_type、avatar 字段。",
|
||||
"subject 包含 id/name;store_type 严格取自 wms_store.project 字段,不再返回 subject_type 兼容字段。",
|
||||
"同一批字段会写入 code 缓存,供 IM 侧 ssoCodeToId 换取并在成功后失效。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.01-system-04",
|
||||
"date": "2026-05-01",
|
||||
"summary": "index.loginToIm 与 ssoCodeToId 改为严格字段模式,不再做兼容回退",
|
||||
"methods": [
|
||||
"index.loginToIm"
|
||||
],
|
||||
"notes": [
|
||||
"loginToIm 仅读取 ctx.user 标准字段:employees_id、employees_name、store_id、store_name、store_type、avatar。",
|
||||
"不再兼容 id/real_name/username/company_name/avatar_url 等历史字段。",
|
||||
"ssoCodeToId 返回值不再使用默认兜底,缺少关键字段时按 code 无效处理。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-01",
|
||||
"date": "2026-05-03",
|
||||
"summary": "将 order.wave.fetch 调整为异步任务提交接口,删除同步返回抓取结果字段",
|
||||
"methods": [
|
||||
"order.wave.fetch"
|
||||
],
|
||||
"notes": [
|
||||
"接口从同步返回抓取结果改为提交任务并异步处理。",
|
||||
"移除原方法中 result_list / total_request_quantity / total_fetched_quantity 等同步返回字段。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-06",
|
||||
"date": "2026-05-03",
|
||||
"summary": "order.wave.batchList:新增 where 支持并限制传入字段",
|
||||
"methods": [
|
||||
"order.wave.batchList"
|
||||
],
|
||||
"notes": [
|
||||
"batchList 新增 where 支持及白名单过滤;禁止传入 warehouse_id/warehouseId。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-08",
|
||||
"date": "2026-05-03",
|
||||
"summary": "order.pendingOrder.allocateStorage 改为异步提交",
|
||||
"methods": [
|
||||
"order.pendingOrder.allocateStorage"
|
||||
],
|
||||
"notes": [
|
||||
"接口变更为异步提交:调用后立即返回 request_id,后端异步执行储位分配;接口不再在响应中同步返回分配明细(如 requested_order_ids、allocated_order_ids 等)。客户端可后续通过任务 ID / 查询链路或事件获取最终分配结果。"
|
||||
],
|
||||
"type": "updated"
|
||||
},
|
||||
{
|
||||
"version": "2026.05.03-system-10",
|
||||
"date": "2026-05-03",
|
||||
"summary": "新增订单批量移出波次接口",
|
||||
"methods": [
|
||||
"order.wave.batchRemoveOrders"
|
||||
],
|
||||
"notes": [
|
||||
"按订单ID批量移出波次;仅处理待处理订单表中非待审核订单(step in [1,2,3])。",
|
||||
"操作在单事务内完成:清空订单的 wave_id/wave_no,并回写 wms_wave_batch 统计(重算 total_orders;当波次被清空时将 wave_status 置为 -1)。",
|
||||
"仓库上下文来自当前登录用户(ctx.user.store_id)。"
|
||||
],
|
||||
"type": "updated"
|
||||
}
|
||||
]
|
||||
|
||||
2207
methods/system.json
2207
methods/system.json
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user